Pimp my Library is a term coined by Martin Odersky explaining how Scala gives you the option of enriching types that you might not own. It comes to mined when you think about how methods can only have receivers in the same package. It turns out it is possible to create methods for receivers you don’t own and hence extend existing types or other libraries. There are other advantages of this of course. Let’s have a look at enriching int. We will just add a method Increment
to int
. This is redundant of course to +1
or ++
but it is a simple example in one hand, and it is immutable on the other.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
func main() {
a := 1
a = RichInt(a).Increment().toInt()
println(a)
}
type RichInt int
func (n RichInt) Increment() RichInt {
return n + 1
}
func (n RichInt) toInt() int {
return int(n)
}
We had to create a new type, but if we have more methods, not just Increment, this seems like an option.
Comments powered by Disqus.