Using Tuples in map, flatmap,… partial functions

前端 未结 3 1951
滥情空心
滥情空心 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:24

    This situation can be understand with the types of inner function.

    First, the type syntax of parameter function for the map function is as follows.

    Tuple2[Int,Int] => B //Function1[Tuple2[Int, Int], B]
    

    The first parameter function is expand to this.

    (t:(Int,Int)) => t._1 + t._2 // type : Tuple2[Int,Int] => Int
    

    This is ok. Then the second function.

    (t:(Int, Int)) => t match {
      case (a:Int, b:Int) => a + b
    }
    

    This is also ok. In the failure scenario,

    (a:Int, b:Int) => a + b 
    

    Lets check the types of the function

    (Int, Int) => Int // Function2[Int, Int, Int]
    

    So the parameter function type is wrong.

    As a solution, you can convert multiple arity functions to tuple mode and backward with the helper functions in Function object. You can do following.

    val l = Seq(("un", ""), ("deux", "hehe"), ("trois", "lol"))
    l map(Function.tupled((b, n) => b + n ))
    

    Please refer Function API for further information.

提交回复
热议问题