scala - Define a type constraint with abstract type -
i try define type constraint abstract type. unfortunately, doesn't compile.
sealed trait matchablevalue { type def value: def assingleitemvalue : itemvalue } sealed trait itemvalue { type def value: } case class stringvalue(value: string) extends itemvalue {type = string} case class stringmatchablevalue(value: string) extends matchablevalue{ type = string override def assingleitemvalue = stringvalue(value) }
unfortunately, 1 doesn't work
def assingleitemvalue[b <: itemvalue](implicit ev: =:= b#a) : b
the aim of type constraint warned @ compile-time of such error :
case class intvalue(value: int) extends itemvalue {type = int} case class intmatchablevalue(value: int) extends matchablevalue{ type = int def assingleitemvalue = stringvalue("error") }
you can accomplish type refinement (note method's return type):
sealed trait matchablevalue { self => type def value: def assingleitemvalue: itemvalue { type = self.a } } sealed trait itemvalue { type def value: } case class stringvalue(value: string) extends itemvalue { type = string } case class intvalue(value: int) extends itemvalue { type = int }
now compiles:
case class stringmatchablevalue(value: string) extends matchablevalue { type = string def assingleitemvalue = stringvalue(value) }
but doesn't:
case class stringmatchablevalue(value: string) extends matchablevalue { type = string def assingleitemvalue = intvalue(1) }
which believe want.
it's worth noting following common pattern when dealing type refinements:
sealed trait matchablevalue { self => type def value: def assingleitemvalue: itemvalue.aux[a] } sealed trait itemvalue { type def value: } object itemvalue { type aux[a0] = itemvalue { type = a0 } }
this same thing, syntax nice alternative if find needing write out type refinement lot.
Comments
Post a Comment