00.scala2014. 3. 28. 13:10
반응형

Scala offers a cool feature where you can rename a class when you import it, including both Scala and Java classes. The basic syntax to rename a class on import looks like this:

import scala.collection.mutable.{Map => MMap}

and this:

import java.util.{HashMap => JavaMap}

If all you needed to know, I hope those "rename on import" syntax examples were helpful.

Why rename a class on import?

An interesting question is, "Why would I want to rename a class on import?"

I've found that I do it to avoid namespace collisions, and/or to make things more clear. For instance, inScala the immutable Map class is imported by default, and if you want to use the mutable version you have to import it manually, as shown here:

# using Map w/o an import gives you an immutable Map
scala> val m = Map("name" -> "Al")
m: scala.collection.immutable.Map[java.lang.String,java.lang.String] = Map(name -> Al)

scala> import scala.collection.mutable.Map
import scala.collection.mutable.Map

# after the import, the same syntax gives you a mutable Map
scala> val m = Map("name" -> "Al")
m: scala.collection.mutable.Map[java.lang.String,java.lang.String] = Map(name -> Al)

This can seem confusing, so one way to work around this confusion -- and make your code more obvious -- is to rename the mutable Map class when you import it. Here's a similar example, but in this case I rename the mutable Map class when I import it:

# at first i get an immutable Map
scala> val m = Map("name" -> "Al")
m: scala.collection.immutable.Map[java.lang.String,java.lang.String] = Map(name -> Al)

# i rename the mutable Map class when i import it
scala> import scala.collection.mutable.{Map => MMap}
import scala.collection.mutable.{Map=>MMap}

# here i still get an immutable Map
scala> val m = Map("name" -> "Al")
m: scala.collection.immutable.Map[java.lang.String,java.lang.String] = Map(name -> Al)

# but here i get a mutable Map by referring to MMap
scala> val m = MMap("name" -> "Al")
m: scala.collection.mutable.Map[java.lang.String,java.lang.String] = Map(name -> Al)

I personally like this approach, because again it makes the code more obvious. You could correctly argue that I could have made it even more obvious if I renamed the class to MutableMap, but in this case I opted for brevity.

Summary

There are many more ways you can use this ability to rename classes when you import them in Scala, and if you have a good example you'd like to share, just leave a note below. Until then, reporting live from Boulder, Colorado, this is Alvin Alexander.

Posted by 1010