Scala 新手在这里。我很困惑为什么下面的代码会抛出异常。我知道 Function1[Int, Int]
有一个摘要 apply
类型方法 Int => Int
这需要定义。下面是不是oddfunc
去做?为什么不x(3)
调用具体apply
oddfunc
中定义的方法?
Welcome to Scala version 2.11.5 (Java HotSpot(TM) 64-Bit Server VM, Java 1.8.0_25).
Type in expressions to have them evaluated.
Type :help for more information.
scala> trait oddfunc extends Function1[Int,Int] {
| def apply(a: Int): Int = a+3
| }
defined trait oddfunc
scala> val x = new oddfunc{}
x: oddfunc = <function1>
scala> x(3)
java.lang.AbstractMethodError: $anon$1.apply$mcII$sp(I)I
at oddfunc$class.apply(<console>:8)
at $anon$1.apply(<console>:8)
... 43 elided
最佳答案
这似乎是在 2.11.4 和 2.11.5 之间引入 Scala 编译器的错误。我降级到 Scala 2.11.4 以查看是否修复了它并且确实如此。
Welcome to Scala version 2.11.4 (Java HotSpot(TM) 64-Bit Server VM, Java 1.8.0_25).
Type in expressions to have them evaluated.
Type :help for more information.
scala> trait oddfunc extends Function1[Int,Int] {
| def apply(a: Int): Int = a+3
| }
defined trait oddfunc
scala> val x=new oddfunc{}
x: oddfunc = <function1>
scala> x(3)
res0: Int = 6
关于scala - 您如何创建抽象 Function1 特征的实现,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28517821/