此代码将函数应用于整数列表,并将选项列表中的每个值设置为值 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))
map 签名:
def map[B, That](f: A => B)(implicit bf: CanBuildFrom[Repr, B, That]): That = {
由于 B 是第一个类型参数(在 map[B, That] 中),这是否意味着它的类型为前缀操作数“l”(列表)?
“A”是如何输入的? scala 编译器是否以某种方式检查 List 'l' 中的类型并推断其类型为 Int ?
“That”是如何输入的?
最佳答案
map
的简单签名在 List[A]
是
def map[B](f: (A) ⇒ B): List[B]
这意味着
-
A
由实际列表的类型参数决定-
Int
对于示例列表l
-
-
B
由函数f
的目标类型决定作为参数传递-
Option[Int]
对于示例函数f: Int -> Option[Int]
-
扩展后的签名为
def map[B, That](f: A => B)(implicit bf: CanBuildFrom[Repr, B, That]): That
它的存在是为了让您可以在可以某种方式遍历的容器之间进行一般性映射,即使目标可遍历的形式与原始形式不同。
A specific example is traversing a
Map
as a container ofPairs
, with a mapping function that produces single values. The resulting traversable is not aMap
anymore, so theCanBuildFrom
implicit parameter is used to find "available representations" for the resulting object.
在此签名中,我们有
-
Repr
作为原始遍历容器的类型 -
B
作为所包含值的目标类型,如简化签名中所示 -
That
作为目标容器的类型,由CanBuildFrom
的隐式存在确定在调用站点使用正确的类型
关于scala - Scala 映射函数签名的解释?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18531887/