4

Scala newbie here. I'm a lot confused about why the below code throws an exception. I know Function1[Int, Int] has an abstract apply method of type Int => Int that needs to be defined. Doesn't the below oddfunc do that? Why doesn't x(3) call the concrete apply method defined in 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
6
  • 1
    That's very strange. On visual inspection, your code seems fine. I cut-and-pasted your exact code into my REPL and it worked perfectly, as expected. Commented Feb 14, 2015 at 16:56
  • Maybe it's an environment thing. Which version of scala are you on? Java? Commented Feb 14, 2015 at 17:01
  • 1
    2.11.0 and 1.7.0_25. But your example is mundane enough that it should really work anywhere. Commented Feb 14, 2015 at 17:33
  • I am not sure, but maybe it is a compiler bug? If you replace trait with class your code works fine on my machine. If I use trait I get the same error. Commented Feb 14, 2015 at 18:50
  • I ran your code with Scala code runner version 2.11.4 and Java version 1.7.0_60 on Yosemite and it does work perfectly fine! Commented Feb 14, 2015 at 19:25

1 Answer 1

2

This does seem like a bug which was introduced into the Scala compiler between 2.11.4 and 2.11.5. I downgraded to Scala 2.11.4 to see if that fixed it and it did.

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
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.