0
votes

I have a Java method which takes in a java.lang.Object. Now I'm trying to pass a Scala Int to it, but the compiler complains about type mismatch of Int and Object.

This feels quite strange as I suppose a Scala Int inherits from AnyRef and should be the same as java.lang.Object?

2

2 Answers

1
votes

Scala Int is not extending AnyRef, though - it extends AnyVal, which is not cast-compatible with java.lang.Object, and is more like Java int. Scala also have Integer class, which is just an alias for java.lang.Integer - use that one if you need to pass it as an object.

1
votes

There're two braches of Scala classes inherited from the Scala root class - Any:

  1. AnyVal: All value based types, e.g. Int, Byte, Double... etc. This is the counterpart of Java raw value classes, i.e. int, float... etc.
  2. AnyRef: All reference based types, e.g. String, List, including boxed Java types, such as java.lang.Integer... etc.

(See diagram in https://docs.scala-lang.org/tour/unified-types.html)

The AnyRef is equivalent to java.lang.Object. Therefore, when calling Java methods taking Object, a AnyVal cannot be directly transferred before boxing. This can be done through explicit type declaration:

JavaClass.methodWithObject(10: java.lang.Integer)

More discussion refer to: Result type of an implicit conversion must be more specific than AnyRef