Scala中->与<-的区别

<-的使用

<-用于for循环中,for (i <- 表达式)例如

scala> val n = 5
n: Int = 5

scala> for (i <- 1 to n)
     | println(i)
1
2
3
4
5

->的使用

用《Scala for the Impatient》中的一段话描述

In Scala, a map is a collection of pairs. A pair is simply a grouping of two values, not necessarily of the same type, such as("Alice", 10).
The -> operator makes a pair.
The value of "Alice" -> 10 is
("Alice", 10)

所以,一般->用来生成map中的key/value pairs,例如

scala> val scores = Map("Alice" -> 10, "Bob" ->3, "Cindy" -> 8)
scores: scala.collection.immutable.Map[String,Int] = Map(Alice -> 10, Bob -> 3, Cindy -> 8)

scala> val newSources = scores + ("Bob" -> 10, "Fred" -> 7)
newSources: scala.collection.immutable.Map[String,Int] = Map(Alice -> 10, Bob -> 10, Cindy -> 8, Fred -> 7)
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容