Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Scala package objects with trait providing type/value aliases

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.

like image 641
virtualeyes Avatar asked May 23 '13 09:05

virtualeyes


1 Answers

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.

like image 132
Nikita Volkov Avatar answered Sep 21 '22 00:09

Nikita Volkov