简体   繁体   中英

Inference of parameter type of function member of generic type in Scala?

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

For such cases in Scala, like in many other languages, the concept of currying exists:

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

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

You also can simplify this with case classes:

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

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

As for your example:

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

You can't do this, both arguments in class declaration have generic B type, so both parameters must have the same type

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM