Jagat
Jagat

Reputation: 1392

Why is it legal to call a method that takes Any without any argument?

Let alone why it's legal, why does this even return true

scala> class Bla { 
    def hello(x: Any): Boolean = x.toString.length == 2 
}
defined class Bla

scala> new Bla().hello() 
res0: Boolean = true 

Upvotes: 5

Views: 86

Answers (1)

Jagat
Jagat

Reputation: 1392

Running with -deprecation gives this

scala> scala> class Bla { 
  def hello(x: Any): Boolean = x.toString.length == 2 
}
defined class Bla

scala> new Bla().hello()
<console>:13: warning: Adaptation of argument list by inserting () has been deprecated: leaky (Object-receiving) target makes this especially dangerous.
        signature: Bla.hello(x: Any): Boolean
  given arguments: <none>
 after adaptation: Bla.hello((): Unit)
       new Bla().hello()
                      ^
res0: Boolean = true

What the warning message means is:

hello() is interpreted as hello(()) and since ().toString = "()", the method returns true.

Upvotes: 5

Related Questions