1

(Really awful title.)

Anyway: can I somehow make Scala infer the type of b in 2nd line?

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 => { })
                           ^

This works as expected after adding the type:

scala> new A("123", (b: String) => { })
res0: A[String] = A@478f6f48

And String is certainly the expected type:

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

1 回答 1

4

对于 Scala 中的这种情况,与许多其他语言一样,存在柯里化的概念:

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

scala> new A("string")(_.toUpperCase)
res8: A[String] = A@5884888a

您还可以使用案例类简化此操作:

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类型,所以两个参数必须具有相同的类型

于 2013-10-03T20:23:11.617 回答