Extension methods in Scala
The idiomatic way to provide extension methods in Scala is via the "Pimp my library" pattern using implicit conversions. That is, if I want to add a method plus
to the Int class all I have to do is define a new type ExtendedInt
with this method and provided an implicit conversion so that, whenever the compiler sees an Int but needs an ExtendedInt it will convert it automatically:
class ExtendedInt(value: Int) {
def plus(other:Int) = value + other
}
implicit def extendInt(i: Int) = new ExtendedInt(i)
Now we can use 1.plus(2)
in our code
I found in this stack overflow thread an easier way to do this in scala 2.10.
implicit class ExtendedInt(val value: Int) extends AnyVal {
def plus(other:Int) = value + other
}
And now we can use 2.plus(2)
in our code
The thread also points to this resources for further understanding of the topic:
Written by Jose Raya
Related protips
Have a fresh tip? Share with Coderwall community!
Post
Post a tip
Best
#Scala
Authors
Related Tags
#scala
Sponsored by #native_company# — Learn More
#native_title#
#native_desc#