Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Scala map explicit type

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!

like image 332
Senua Avatar asked Sep 17 '18 09:09

Senua


People also ask

What does => mean in Scala?

=> is the "function arrow". It is used both in function type signatures as well as anonymous function terms. () => Unit is a shorthand for Function0[Unit] , which is the type of functions which take no arguments and return nothing useful (like void in other languages).

Are maps mutable in Scala?

Maps are classified into two types: mutable and immutable. By default Scala uses immutable Map. In order to use mutable Map, we must import scala.

Which of the following categories does the scala map operations apply?

The fundamental operations on maps are similar to those on sets. They are summarized in the following table and fall into the following categories: Lookup operations apply , get , getOrElse , contains , and isDefinedAt . These turn maps into partial functions from keys to values.

How do you access map elements in Scala?

Scala Map get() method with exampleThe get() method is utilized to give the value associated with the keys of the map. The values are returned here as an Option i.e, either in form of Some or None. Return Type: It returns the keys corresponding to the values given in the method as argument.


1 Answers

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.

like image 164
jwvh Avatar answered Oct 26 '22 09:10

jwvh