2013-10-03 158 views
1

(真的很糟糕的标题)在Scala中泛型类型的函数成员参数类型的推断?

无论如何:我可以以某种方式让Scala推断第二行中的b的类型吗?

scala> class A[B](val b: B, val fun: B => Unit) 
defined class A 

scala> new A("123", b => { }) 
<console>:9: error: missing parameter type 
       new A("123", b => { }) 
         ^

这个工程将类型后预期:

scala> new A("123", (b: String) => { }) 
res0: A[String] = [email protected] 

而且String肯定是预期的类型:

scala> new A("123", (b: Int) => {}) 
<console>:9: error: type mismatch; 
found : Int => Unit 
required: String => Unit 
       new A("123", (b: Int) => {}) 
            ^

回答

4

对于这样的情况在Scala中,像在许多其他语言,柯曲的概念存在:

scala> class A[B](val b: B)(val fun: B => Unit) 
defined class A 

scala> new A("string")(_.toUpperCase) 
res8: A[String] = [email protected] 

您也可以用case类简化此:

scala> case class A[B](b: B)(fun: B => Unit) 
defined class A 

scala> A("string")(_.toUpperCase) 
res9: A[String] = A(string) 

至于你的例子:

new A("123", (b: Int) => {}) 

你不能做到这一点,在类声明两个参数有通用型B,这样既参数必须具有相同的类型

+0

谢谢,我会使用柯里里,如你所建议的。 :)(但我还是不明白,为什么不能在我的例子中推导这个类型。) –

+2

@MichałRus这是对Scala类型推断的一个限制,你不能对这个 – 4lex1v

+0

Kthx做任何事情。 :)漂亮的头发,顺便说一句。 –