Reputation: 65
I'm new in Scala and programming in general.. I have troubles with the Scala map function..
The simple signature of the map function is: def map[B](f: (A) ⇒ B): List[B]
So i guess the B of map[B] is generic and i can explicit set the type of the result?
If i try to run the code:
val donuts1: Seq[Int] = Seq(1,2,3)
val donuts2: List[Int] = {
donuts1.map[Int](_ => 1)
}
i got the error message "expression of type int doesn't conform to expexted type B"
I don't understand the problem here.. Could someone explain the problem?
Thank you!
Upvotes: 5
Views: 623
Reputation: 51271
The map()
signature quoted in your question is a simplified/abbreviated version of the full signature.
final def map[B, That](f: (A) ⇒ B)(implicit bf: CanBuildFrom[List[A], B, That]): That
So if you want to specify the type parameters (which is almost never needed) then you have to specify both.
val donuts1: List[Int] = List(1,2,3)
val donuts2: List[Int] = donuts1.map[Int,List[Int]](_ => 1)
//donuts2: List[Int] = List(1, 1, 1)
and i can explicit set the type of the result?
Not really. The type parameter has to agree with what the f
function/lambda returns. If you specify the type parameter then you're (usually) just asking the compiler to confirm that the result type is actually what you think it should be.
Upvotes: 6