编译器不接受将元组直接传递给构造函数,如最小示例所示:
scala> case class A(a:Int, b:Int)
defined class A
scala> List((1, 2)).map(A)
<console>:14: error: type mismatch;
found : A.type
required: ((Int, Int)) => ?
List((1, 2)).map(A)
^
scala> List((1, 2)).map(A _)
<console>:14: error: _ must follow method; cannot follow A.type
List((1, 2)).map(A _)
^Scala解析器组合子的运算符是^^。在fastparse库中有类似的东西吗?
发布于 2020-07-22 12:37:01
你在找.tupled
List((1, 2)).map(A.tupled)这不能“开箱即用”的原因是因为A需要两个Int类型的参数,而不是(Int, Int)的元组。tupled将(A, A)提升到((A, A))中。
可以通过修改A的构造函数来验证这一点:
final case class A(tup: (Int, Int))然后这个就行了:
List((1, 2)).map(A)发布于 2020-07-22 12:37:14
这是因为以下原因:
List((1, 2)).map(A)翻译为:
List((1, 2)).map(x => A(x))但是A构造函数接受两个整数作为参数,而不是Tuple2[Int, Int]。您必须定义一个接受两个整数的元组的构造函数。
https://stackoverflow.com/questions/63026912
复制相似问题