38

Suppose I have the following java method

protected void onEvent(Object obj) {

    }

The Scala compiler accepts

protected override def onEvent(event: Any)

and

protected override def onEvent(event: Object)

Is there any difference between the two?

deltanovember
  • 42,611
  • 64
  • 162
  • 244

2 Answers2

26

Any includes things that are not Objects in Java; it includes primitive types and also Nothing. Object is the same class as in Java, so it definitely excludes primitives.

Ernest Friedman-Hill
  • 80,601
  • 10
  • 150
  • 186
  • 8
    So if you are attempting to a Java method that uses Object, does Any get you into trouble if you pass in a primitive or is it implicitly converted? – James McMahon Jul 15 '12 at 14:19
  • 1
    @James i tried `def met(a: java.lang.Object) = {}; val i = 10; met(i)` and here's the output from compiler: *error: the result type of an implicit conversion must be more specific than AnyRef* http://stackoverflow.com/a/26550576/4541480, it worked with `val i: java.lang.Integer = 10` (not with default `val i: Int = 10` – Nicofisi Mar 18 '17 at 13:50
26

There is an article on scala-lang with great diagram (I even put it on the wall). And also need to be mentioned:

If Scala is used in the context of a Java runtime environment, then scala.AnyRef corresponds to java.lang.Object.

4e6
  • 10,696
  • 4
  • 52
  • 62