繁体   English   中英

Scala中泛型类型的函数成员的参数类型的推断?

[英]Inference of parameter type of function member of generic type in 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] = A@478f6f48

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

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

对于Scala中的此类情况,就像许多其他语言一样,存在currying概念:

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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