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)?
Asked
Active
Viewed 132 times
4
-
see also http://jackcoughonsoftware.blogspot.ru/2009/01/deeper-look-at-apply-method-in-scala.html – om-nom-nom Mar 04 '13 at 14:23
1 Answers
7
This can be done via apply
method:
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
- 62,329
- 13
- 183
- 228
-
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