scala - Type Constraints with 2 Parameters -
given:
scala> sealed trait parent defined trait parent scala> case object k extends parent defined object k scala> case object j extends parent defined object j scala> sealed trait result defined trait result scala> case object kresult extends result defined object kresult scala> case object jresult extends result defined object jresult
how can implement following f
?
scala> def f[a <: parent, b <: result](x: a): b = ??? f: [a <: parent, b <: result](x: a)b
let's k
must have kresult
, , j
has jresult
.
but, concern there's no enforced constraint on passing f[k, jresult]
@ compile-time.
or, perhaps resort to:
def f(x: parent): result = x match { case k => kresult case j => jresult
but, weakness of approach make mistake:
def badf(x: parent): result = x match { case k => jresult case j => kresult
?
you need way link kresult
k
in type system. can achieve adding type parameter a
result
(optionally, can have upper-bound of parent
, may not necessary).
sealed trait parent case object k extends parent case object j extends parent sealed trait result[a] case object kresult extends result[k.type] case object jresult extends result[j.type]
then, b
can bounded result[a]
, enforce fact if a = k
, b <: result[k]
.
def f[a <: parent, b <: result[a]](x: a): b = ??? scala> f[k.type, result[j.type]](k) <console>:16: error: type arguments [k.type,result[j.type]] not conform method f's type parameter bounds [a <: parent,b <: result[a]] f[k.type, result[j.type]](k) ^
such method doesn't make lot of sense though, because there no way infer result type, must manually supplied. still, how enforce constraints.
Comments
Post a Comment