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
答案 0 :(得分:2)
这看起来像是在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