Stefan Koch Stefan Koch - 2 months ago 9
Scala Question

Creating a CanBuildFrom in Scala

I'm starting to learn Scala and have an issue with

.map
. I think I need to define a CanBuildFrom by hand, but I have no idea how to do it. I have had a look at some introductions, but while I understand the purpose, I cannot figure out an implementation.

So to shorten my code, I have defined a type alias.

type Dice = Vector[(Int,Int)]


I have created an implicit class to add methods to that Vector.

implicit class DiceMethods(dice: Dice){
private def d(x : Int) = // some method

def roll : Dice = dice map( case (x: Int, y: Int) => (0, d(x) + y) )
}


The compiler screams at me, when I use
map
.So i guess, I need an
implicit object someFunkyName extends CanBuildFrom
but the rest is beyond me. Or maybe there is some other problem.

Answer

You need not worry about CanBuildFrom

use map { case .... } instead of map ( case ...)

implicit class DiceMethods(dice: Dice){  
     private def d(x : Int) = // some method

     def roll : Dice = dice map { case (x: Int, y: Int) => (0, d(x) + y)  }
   }
Comments