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? ie 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.


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 (ie traits and classes) and value (ie objects, packages and values). You cover them both.

链接地址: http://www.djcxy.com/p/82694.html

上一篇: 为了存在而需要隐含的特质或类?

下一篇: Scala包含提供类型/值别名特征的对象