Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

methods inherited from Object are rendered ambiguous

Tags:

scala

val x: AnyRef = 42

type mismatch: found Int(42) required: AnyRef

Note: an implicit exists from scala.Int => java.lang.Integer, but methods inherited from Object are rendered ambiguous. This is to avoid a blanket implicit which would convert any scala.Int to any AnyRef.

You may wish to use a type ascription: x: java.lang.Integer

I don't understand the emphasized part. What methods are rendered ambiguous, and how come? Are methods inherited from Object always "rendered ambiguous" in Scala? Is this a special scenario where methods somehow wind up multiple times in a type? I just don't see where the ambiguity comes from.

like image 733
fredoverflow Avatar asked Nov 01 '22 01:11

fredoverflow


1 Answers

Scala has to pretend that Int is in a different place in the inheritance hierarchy than Java places it. This results in some awkwardness.

Consider the method notify. Waiting on an Int doesn't work--it's a primitive. Waiting on a newly-boxed java.lang.Integer doesn't work either, since the other threads may have ended up with their own separately-boxed Integers. You just don't want notify to work on an Int--it's the wrong thing to do.

But if you have the conversion Int => java.lang.Integer without anything unusual, you will be able to call notify on your Int.

To prevent this sort of usually-wrong behavior, the mechanism for failing to resolve a conversion due to ambiguity is hijacked. This keeps Int => java.lang.Integer serving to convert Int where AnyRef is expected (which would break the inheritance hierarchy), and prevents things like 42.notifyAll from working since even though java.lang.Integer has that method, the inferencing machinery is kept from noticing it.

The message you see is supposed to cover both the 42.notify case than the 42: AnyRef case.

like image 68
Rex Kerr Avatar answered Nov 15 '22 05:11

Rex Kerr