Question

What is the "correct" way to alias an object in Scala?

For example, let's say I need a RoleGroup in scope in various parts of my application (which is broken up into SBT sub projects)

trait RoleGroup
object RoleGroup {
  case object ADMIN     extends RoleGroup
  case object MEMBER    extends RoleGroup
  case object PUBLIC    extends RoleGroup
}

Since I don't want to repeatedly import RoleGroup, I decided to alias RoleGroup trait and object into type and val counterparts like so:

package com.developer
package controller

trait ControllerBase {
  type RoleGroup    = controller.RoleGroup
  val RoleGroup     = controller.RoleGroup
  ...
}

and then sub project package objects can extend the helper trait to get the imports for free:

package com.client

package object member
  extends com.developer.controller.ControllerBase

Am doing the same for other case objects that need to be in scope. Is this a sensible solution? i.e. are there any drawbacks/issues I need to be aware of? Everything compiles and browser test pages appear to run just as in pre-refactored application, but am not sure if this is the best approach.

Was it helpful?

Solution

It's a sensible approach. In fact it's being applied in the Scala library itself.

There are just two imaginable levels of members you need to alias: type (i.e. traits and classes) and value (i.e. objects, packages and values). You cover them both.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top