Is there a pattern in Scala that adds 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 implicitly converting Int to RichInt. But this is impossible to do, since the array is the final class.

+4
source share
2 answers

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

 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 
+11
source

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

Thus, you can freely define implicit conversions for Array with one key condition: you must abandon Scala's built-in implicit transform from Array to ArrayOps (only in Scala 2.8).

+6
source

Source: https://habr.com/ru/post/1308966/


All Articles