val x: AnyRef = 42
type mismatch: found
Int(42)
required:AnyRef
Note: an implicit exists from
scala.Int => java.lang.Integer
, but methods inherited fromObject
are rendered ambiguous. This is to avoid a blanket implicit which would convert anyscala.Int
to anyAnyRef
.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.
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 Integer
s. 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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With