2

Here why String taken high priority than AnyRef while calling with null value?

class Test {
  def m1(s: String): Unit = {
    println("String version")
  }

  def m1(o: AnyRef): Unit = {
    println("AnyRef version")
  }
}

object Demo {
  def main(args: Array[String]): Unit = {
    val t: Test = new Test()
    t.m1("arun")
    t.m1(new AnyRef())
    t.m1(null)
  }
}

output

String version
AnyRef version
String version
Nireekshan
  • 317
  • 1
  • 11
  • 2
    thats because scala compiler will match with lowest subtype available. lowest subtype of AnyRef that matches with null is String – Ramesh Maharjan Apr 30 '18 at 07:59
  • So, instead of AnyRef, if i replaced with StringBuffer than facing error like, "overloaded method value m1 with alternatives:", what is mean? – Nireekshan Apr 30 '18 at 08:04
  • Possible duplicate of [Ambiguous Reference to overloaded definition - One vs Two Parameters](https://stackoverflow.com/questions/16829114/ambiguous-reference-to-overloaded-definition-one-vs-two-parameters) – Ramesh Maharjan Apr 30 '18 at 08:35

2 Answers2

0

So here is what i feel is happening. Null is a subtype of all reference types; its only instance is the null reference. Like any other reference type when the compiler looks to pass null into a method it does look for implicits for available conversions to the target type which in this case is String. And it appears there is an implicit available for this to avoid running into nullpointer exceptions.

If you print out the string inside the def m1(s: String): Unit method you would see there is no exception caused because of this passing.

The other method def m1(s: AnyRef): Unit would only execute if there were no available conversions.

Som Bhattacharyya
  • 3,972
  • 35
  • 54
0

The Scala compiler is looking for the lowest common subtype available. In your case it is String, since String is a subtype of AnyRef. Here is Scala type hierarchy:

enter image description here

Noam Shaish
  • 1,613
  • 2
  • 16
  • 37