Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 390
Fred Haslam Avatar asked Dec 04 '22 12:12

Fred Haslam


2 Answers

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
like image 75
Rex Kerr Avatar answered Jan 30 '23 06:01

Rex Kerr


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).

like image 31
Randall Schulz Avatar answered Jan 30 '23 07:01

Randall Schulz