views:

118

answers:

2

Is there a Pattern in Scala that can add a method to an Array object?

I am thinking of the implicit conversion of Int to RichInt. But that can't be done as Array is a final class.

+6  A: 

Implicit conversions are not prevented by the final-ness of the input class. String, for example, has an implicit conversion to RichString (Scala 2.7) or StringOps (Scala 2.8).

So you're free to define implicit conversions for Array with one key caveat: You must forgo Scala's built-in implicit conversion from Array to ArrayOps (in Scala 2.8 only).

Randall Schulz
+11  A: 

As long as you avoid name collisions with any other implicit on Array (e.g. ArrayOps in 2.8, which adds the collections methods), you can extend using the normal implicit pimp-my-library pattern:

class FooArray[T](at: Array[T]) {
  def foo() = at.length*at.length
}
implicit def array2foo[T](at: Array[T]) = new FooArray(at)
scala> Array(1,2,3).foo
res2: Int = 9
Rex Kerr