所以我有一个元组,我想作为Scala中的case类的参数传递。对于没有类型参数的case类,这很容易,我可以这样做:
scala> case class Foo(a: Int, b: Int)
defined class Foo
scala> (Foo.apply _)
res0: (Int, Int) => Foo = <function2>
scala> val tuple = (1, 2)
tuple: (Int, Int) = (1,2)
scala> res0.tupled(tuple)
res1: Foo = Foo(1,2)
scala> Foo.tupled(tuple)
res2: Foo = Foo(1,2)
但是,如果case类具有类型参数,则它似乎不起作用:
scala> (Bar.apply _)
res26: (Nothing, Nothing) => Bar[Nothing] = <function2>
scala> res26.tupled(tuple)
<console>:18: error: type mismatch;
found : (Int, Int)
required: (Nothing, Nothing)
res26.tupled(tuple)
^
scala> (Bar[Int].apply _)
<console>:16: error: missing arguments for method apply in object Bar;
follow this method with `_' if you want to treat it as a partially applied function
(Bar[Int].apply _)
scala> Bar.tupled(tuple)
<console>:17: error: value tupled is not a member of object Bar
Bar.tupled(tuple)
^
scala> Bar[Int].tupled(tuple)
<console>:17: error: missing arguments for method apply in object Bar;
follow this method with `_' if you want to treat it as a partially applied function
Bar[Int].tupled(tuple)
^
如何使用类型参数部分应用案例类?我正在使用Scala 2.10.3。
答案 0 :(得分:4)
这似乎有效:
scala> case class Foo[X](a:X, b: X)
defined class Foo
scala> Foo.apply[Int] _
res1: (Int, Int) => Foo[Int] = <function2>
scala>