LoginSignup
0

More than 5 years have passed since last update.

applyをtraitで実装する

Last updated at Posted at 2017-10-06

traitでapplyを実装して、初期化処理を共通化したくなりました。 :airplane:

要件としては、Identifier[_]を継承したIDクラスを引数なしでapplyすると値が自動生成されてほしい。

以下のようにすると、できた気がする :angel:

trait Identifier[+A] {
  def value: A
}

trait StringIdentifierCompanion[A <: Identifier[_]] {
  def prefix: String
  def apply(value: String): A
  def apply(): A = this.apply(this.generateId)
  def generateId: String = s"${prefix}-${UUID.randomUUID.toString}" // WIP
}

final case class UserId(value: String) extends Identifier[String]

case object UserId extends StringIdentifierCompanion[UserId] {
  override def prefix: String = "USER"
}

StringIdentifierCompanionのtraitでdef apply(value: String): Aが定義されていますが、UserIdのコンパニオンオブジェクトなので、メソッドが自動生成され、わざわざ定義しなくても動く。

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0