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 see this output:

 
class PoliceOfficer

The type of the instance still reflects its true identity, but the conversational name Cop is aliased to that class name only within the scope of our file.

In the Scala library a variety of classes have been aliased. Sometimes the alias is used to give better names and at other times it’s used to refer to certain classes in select packages. For instance, Set is an alias that refers to the version of Set in the immutable package instead of the version in the mutable package.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.145.177.115