从CaseClass(Int,String)创建函数[Int,String,CaseClass] #tupled?

时间:2015-12-30 17:17:55

标签: scala

假设:

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) } 
     | }
<console>:18: error: constructor cannot be instantiated to expected type;
 found   : (T1, T2)
 required: ((Int, String)) => Foo
         case (param1, param2)  => { (param1, param2) => Foo(param1, param2) }

但是,它不起作用。我该如何解决这个破碎的代码?

1 个答案:

答案 0 :(得分:5)

我不确定这场比赛应该做什么。你不需要它。要创建MyModel(models.Model): KEY1 = 'Key1' KEY2 = 'Key2' ATTRIBUTE_CHOICES = ( (KEY1, 'Label 1'), (KEY2, 'Label 2')) attribute = models.CharField(max_length=4, choices=ATTRIBUTE_CHOICES, default=KEY1) ,请使用.tupled,如下所示:

Function1[(Int, String), Foo]

如果您需要scala> case class Foo(x: Int, y: String) defined class Foo scala> val f = Foo.tupled f: ((Int, String)) => Foo = <function1> scala> f((1, "x")) res0: Foo = Foo(1,x) ,则无需使用.tupled 。具有N个参数的案例类的伴随对象已经实现了FunctionN特征。

Function2[Int, String, Foo]