鉴于:
scala> case class Foo(x: Int, y: String) defined class Foo
我正在尝试Foo.tupled
用来创建Function2[Int, String, Foo]
:
scala> val fn2: Function2[Int, String, Foo] = Foo.tupled match { | case (param1, param2) => { (param1, param2) => Foo(param1, param2) } | }:18: error: constructor cannot be instantiated to expected type; found : (T1, T2) required: ((Int, String)) => Foo case (param1, param2) => { (param1, param2) => Foo(param1, param2) }
但是,它不起作用.我该如何解决这个破碎的代码?
我不确定比赛应该做什么.你不需要它.要创建一个Function1[(Int, String), Foo]
,请使用如下的.tupled:
scala> case class Foo(x: Int, y: String) defined class Foo scala> val f = Foo.tupled f: ((Int, String)) => Foo =scala> f((1, "x")) res0: Foo = Foo(1,x)
如果你想Function2[Int, String, Foo]
,你不需要使用.tupled 可言.具有N个参数的案例类的伴随对象已经实现了FunctionN特征.
scala> val x: Function2[Int, String, Foo] = Foo x: (Int, String) => Foo = Foo scala> :javap -c Foo$ Compiled from "" public class Foo$ extends scala.runtime.AbstractFunction2 implements scala.Serializable { public static final Foo$ MODULE$;