O'Reilly logo

Pragmatic Scala by Venkat Subramaniam

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Type Aliasing

When working with a large library you may come across a class name that simply does not work for you. The name is either long or unwieldy, or you simply feel there is a better name that captures the abstraction. You have the freedom to alias, and give the class the name that will make you feel good.

Here’s a class with a rather long name:

WorkingWithObjects/PoliceOfficer.scala
 
class​ PoliceOfficer(​val​ name: ​String​)

Cop says it all and is easier to type as well. Here’s how we can alias the PoliceOfficer class without losing its identity:

WorkingWithObjects/CopApp.scala
 
object​ CopApp ​extends​ App {
 
type​ Cop = PoliceOfficer
 
 
val​ topCop = ​new​ Cop(​"Jack"​)
 
println(topCop.getClass)
 
}

Compile and run the code to ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required