Scala中=>和->之间的区别

我正在浏览Internet上的一些Scala教程,并且注意到在某些示例中,作者在HOF(高阶函数)中同时使用了=>和->。

示例:

val vec = Vector("hello","world").map(s => s -> s.length)
// vec: scala.collection.immutable.Vector[(String,Int)] = 
// Vector((hello,5),(world,5))

Scala中 => -> 有什么区别?

trydiy 回答:Scala中=>和->之间的区别

-> 它用于通过使用隐式转换(例如元组,映射等)将键与值关联。

scala> 1 -> 2
res0: (Int,Int) = (1,2)

scala> val map = Map("x" -> 12,"y" -> 212)

它基本上只是拿左边的物品,然后将其映射到右边的物品

它使用隐式转换将任何类型转换为“ ArrowAssoc”的实例

implicit def any2ArrowAssoc[A](x: A): ArrowAssoc[A] = new ArrowAssoc(x)


class ArrowAssoc[A](x: A) {
    def -> [B](y: B): Tuple2[A,B] = Tuple2(x,y)
}

=> 是该语言本身提供的一种语法,用于使用按名称调用来创建函数实例。 它在方法内部传递值名称,例如:

`def f(x:Int => String) {}` function take argument of type Int and return String

您也不能像下面那样传递任何参数

() => T means it doesn't take any argument but return type T

,

->用于隐式转换提供的方法,并且key->value创建一个元组(键,值)。

=>用于函数类型,函数文字和导入重命名。

本文链接:https://www.f2er.com/3031615.html

大家都在问