Scala generics implementing Ordered[A[B]] gives strange compiler errors -
i have strange error message, , cannot fix asinstanceof[t]
trait abase { type <: abase def compare(that: a): int } case class b [a <: abase] (somefield: a) { //extends ordered[b[a]] { def compare1(that: b [a]): int = somefield.asinstanceof[a].compare(that.somefield.asinstanceof[a]) /*error: type mismatch; found : required: _1.a val _1: = somefield.asinstanceof[a].compare(that.somefield.asinstanceof[a])*/ def compare2(that: b [a]): int = somefield.compare(that.somefield.asinstanceof[a]) /*error: type mismatch; found : required: b.this.somefield.a = somefield.compare(that.somefield.asinstanceof[a])*/ def compare3(that: b [a]): int = somefield.compare(that.somefield) /*error: type mismatch; found : that.somefield.type (with underlying type a) required: b.this.somefield.a = somefield.compare(that.somefield)*/ }
error itself
error: type mismatch; found : required: _1.a val _1: a
you can fix casting b's (this) somefield
type:
trait abase { type <: abase def compare(that: a): int } case class b [a <: abase] (somefield: a) { def compare1(that: b [a]): int = somefield.compare(that.somefield.asinstanceof[this.somefield.a]) def compare2(that: b [a]): int = somefield.compare(that.somefield.asinstanceof[this.somefield.a]) def compare3(that: b [a]): int = somefield.compare(that.somefield.asinstanceof[this.somefield.a]) }
you can keep type attribute make more concise:
case class b [a <: abase] (somefield: a) { type thisa = this.somefield.a def compare1(that: b [a]): int = somefield.compare(that.somefield.asinstanceof[thisa]) def compare2(that: b [a]): int = somefield.compare(that.somefield.asinstanceof[thisa]) def compare3(that: b [a]): int = somefield.compare(that.somefield.asinstanceof[thisa]) }
Comments
Post a Comment