Scala – Why Does Scala Use the ‘_’ Operator for Package Import Instead of ‘*’?

javascala

In my opinion, one of the greatest things about Scala is its interoperability with Java and its similar syntax. One thing that I found strange is the use of the _ operator for package wilcard imports instead of the * operator that is used in Java.

Is there a technical reason for using _ instead of *? If not, then why was this change done?

Best Answer

In Scala, the * is a valid identifier. One could write:

val * = "trollin'"
println(*)

With the result being:

trollin'

One could write a class named * as such:

class * {
  def test():String = {
    "trollin'"
  }
}

So with that being the case, when I have a class * in the package us.hexcoder and I write:

import us.hexcoder.*

You would be saying that you wish to import a class with the name *. Because of this, Scala needed to use another symbol to indicate a wildcard import. For whatever reason, they decided to use _ as the wildcard symbol.