0

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?

peidaqi
  • 673
  • 1
  • 7
  • 18
  • Possible duplicate of [What is the differences between Int and Integer in Scala?](https://stackoverflow.com/questions/1269170/what-is-the-differences-between-int-and-integer-in-scala) – Alex Savitsky Jul 25 '18 at 19:26

2 Answers2

1

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.

Alex Savitsky
  • 2,306
  • 5
  • 24
  • 30
1

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

peidaqi
  • 673
  • 1
  • 7
  • 18