Using Tuples in map, flatmap,… partial functions

前端 未结 3 1950
滥情空心
滥情空心 2020-12-19 18:17

If I do:

val l = Seq((\"un\", \"\"), (\"deux\", \"hehe\"), (\"trois\", \"lol\"))
l map { t => t._1 + t._2 }

It\'s ok.

If I d

3条回答
  •  醉话见心
    2020-12-19 18:47

    The type of a function argument passed to map function applied to a sequence is inferred by the type of elements in the sequence. In particular,

    scenario 1: l map { t => t._1 + t._2 } is same as l map { t: ((String, String)): (String) => t._1 + t._2 } but shorter, which is possible because of type inference. Scala compiler automatically inferred the type of the argument to be (String, String) => String

    scenario 2: you can also write in longer form

    l map { t => t match {
        case(b, n) => b + n
      }
    }
    

    scenario 3: a function of wrong type is passed to map, which is similar to

    def f1 (a: String, b: String) = a + b
    
    def f2 (t: (String, String)) = t match { case (a, b) => a + b }
    
    l map f1 // won't work
    
    l map f2
    

提交回复
热议问题