4

Let's say I have a class MyList in scala, with a list as a private member. Is it possible to define "()" for my class to return the expected thing in case of positive index given, and starting from end in case of negative (just like in python)?

user1377000
  • 1,313
  • 2
  • 14
  • 27

1 Answers1

7

This can be done via applymethod:

class PythonicArray {
   private val underlying = Array(1,2,3,4)

   def apply(n: Int) = {
    val i = if (n < 0) (underlying.length + n) else n
    underlying(i)
   } 
}
om-nom-nom
  • 60,231
  • 11
  • 174
  • 223
  • I usually do this as a one-liner with exactly the same content: `def apply(n: Int) = underlying(if (n<0) n+underlying.length else n)` – Rex Kerr Mar 04 '13 at 17:01
  • `apply` is a special method name. It can be used both in objects and classes. Not only is the name `apply` special when used as a method name, there is also a complementary `unapply` special method name, used when extracting the parts in a class for pattern matching etc. Be careful not to abuse `apply` - the principle of least surprise should probably apply. – Rick-777 Mar 05 '13 at 14:26