Explanation Scala signature card function?

This code applies the function to the List of Ints and sets each value in the parameter list with a value of 4:

val l = List(1,2,3,4,5) //> l : List[Int] = val v = 4 //> v : Int = 4 def g(v:Int) = List(v-1, v, v+1) //> g: (v: Int)List[Int] l map (x => {f(x);}) //> res0: List[Option[Int]] = List(Some(4), Some(4), Some(4), Some(4), Some(4)) 

Card Signature:

  def map[B, That](f: A => B)(implicit bf: CanBuildFrom[Repr, B, That]): That = { 

Since B is a parameter of the first type (on the map [B, That]), does this mean that it is typed on the prefix operand 'l' (List)?

How is β€œA” dialed? The scala compiler somehow checks the type in the list "l" and concludes that its type is Int?

How is β€œThis” typed?

+2
source share
1 answer

The simple signature for map in List[A] is

 def map[B](f: (A) β‡’ B): List[B] 

which means that

  • A determined by the type parameter of the actual list
    • Int for a list of examples l
  • B determined by the target type of function f passed as an argument
    • Option[Int] for the example function f: Int -> Option[Int]

Extended Signature

 def map[B, That](f: A => B)(implicit bf: CanBuildFrom[Repr, B, That]): That 

which exist in such a way that you can outline in general terms between containers that can be traversed in some way, even if the target moveable has a different shape than the original.

A specific example is moving a map as a Pairs container, with a display function that produces single values. The resulting traversable is no longer a map , so the CanBuildFrom implicit parameter is used to search for "available views" for the resulting object.

In this signature we have

  • Repr as the type of source container passed
  • B as the target type of the contained values, as in a simplified signature
  • That as the type of target container, determined by the implicit existence of CanBuildFrom with the correct types on the call site
+7
source

Source: https://habr.com/ru/post/1501741/


All Articles