Last Updated: February 25, 2016
·
2.296K
· sksamuel

Scala Alias Pattern

Here is a quick tip for when you have many objects that you want to bring into scope in without having multiple imports over and over. Particularly useful for enum style constructs.

Let's say you have the following definitions

package com.sksamuel.role
trait Role
object Role {
  case object Admin extends Role
  case object Developer extends Role
  case object Staff extends Role
  case object Customer extends Role
}

Then make a trait that aliases both the type and the values.

package com.sksamuel.role
trait Roles {
    val Role = otherpackage.Role
    type Role = otherpackage.Role
}

Now you can of course mix in the trait to get the imports, but we can go a step further and mix in the trait with a package object to get the imports for free in the entire package.

package com.sksamuel.elsewhere
package object elsewhere extends com.sksamuel.role.Roles

Now the imports are available to everything in the com.sksamuel.elsewhere package.