Possible Duplicate:
scala: adding a method to List?
I struggle to formulate what I’m trying to do, but the code example should be pretty straightforward. If anyone knows a better way to phrase it, you are free to edit the title. 🙂
trait DiceThrow {
list: List[Int] => // something like this??
def yatzee = list.filter(_ == list.head).length >= 5
}
object Main extends App {
val aThrow = List(4,4,4,4,4) with DiceThrow
aThrow.yatzee // => true is what I want
}
So I want the aThrow: List[Int] to have some extra methods, like knowing whether it’s a yatzee or not. This is just one example I made up where adding some extra methods to e.g. a List could be useful.
Is this possible somehow? Or is there another approach that’s more the scala way? I believe it’s possible with implicit conversion(?)(they’re still pretty “magic” to me), but that seems unnecessarily dirty this use-case?
You can use enrich (pimp) my library pattern:
In scala 2.10 it could be simplified with implicit classes:
Then you could use it like: