美文网首页Scala数客联盟
Scala中->与<-的区别

Scala中->与<-的区别

作者: Woople | 来源:发表于2016-10-06 15:23 被阅读0次

    <-的使用

    <-用于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)
    

    相关文章

      网友评论

        本文标题:Scala中->与<-的区别

        本文链接:https://www.haomeiwen.com/subject/oeveyttx.html