Home Pimp My Library Pattern
Post
Cancel

Pimp My Library Pattern

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.


Resources

  1. Ultimate Go Programming
  2. The Go Programming Language
  3. Go Documentation
  4. A tour of Go
  5. Go wiki: Switch
  6. The Go Programming Language Specification
  7. Go by Example
  8. Pimp My Library ~ Martin Odersky
This post is licensed under CC BY 4.0 by the author.
Contents

Methods

Functions

Comments powered by Disqus.