Scala 中 => 和 -> 的区别
Difference between => and -> in 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 中 => 和 -> 有什么区别?
->用于隐式转换提供的方法&key->value
创建元组(key,value)。
=> 用于函数类型、函数文字和导入重命名。
-> 它用于通过使用隐式转换将键与值相关联,例如元组、映射等
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
.
我刚刚浏览了 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 中 => 和 -> 有什么区别?
->用于隐式转换提供的方法&key->value
创建元组(key,value)。
=> 用于函数类型、函数文字和导入重命名。
-> 它用于通过使用隐式转换将键与值相关联,例如元组、映射等
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
.