collections - In Scala, member of a class is not found when its instance is accessed from a list [Class] -
i have feeling problem facing has type erasure of scala, newbie can't set fingers on it. need help here.
first, code:
class c (val i: int) { def mkstring() = { println("c.i =" + this.i) } object c { implicit val cordering = new ordering [c] { def compare (a: c, b: c)= { a.i compare b.i; } }
then, create class holds collection of class 'c' thus:
class containerofc [c] (s:int) (implicit ordering: cordering[c]) { var internalcollection = new treeset[c]() def + (c:c): containerofc [c] = { this.internalcollection += c } def mkstringofelems () = { val y = this.internalcollection.tolist println (y.head.i) // <--- problem here } }
this repl tells me:
error: value not fellow member of type parameter c println(y.head.i) ^
i have checked type of 'y' out there: list[c]. if so, why not allowed access 'i'? construction parameter alright, val , hence, can treated fellow member variable, can't be?
i have gone through few of other related posts in forum, , manifests , typetags possible ways out here. but, not sure if need go level simple use-case.
this have unusual , familiar feeling of "been there, done that".
how seek alter this:
class containerofc [c] (s:int) (implicit ordering: cordering[c]) { ... }
to without type parameter c
in declaration :
class containerofc(s:int) (implicit ordering: cordering[c]) { ... }
the code showed created class , specific type c
. when later write class containerofc[c]
, c
type parameter named other identifier. same defining class containerofc[a]
a
not have relation class/type c
defined in before code. in illustration type parameter c
shadow name of class defined earlier... error message indicating c
not have value i
, that's because compiler not referring same c
thinking of.
edit: know if on same page without getting bogged downwards in other compilation errors, here few edits create code compile , using more commonly used indentation , brace style:
class c(val i: int) { def mkstring() = println("c.i =" + this.i) } object c { implicit val cordering = new ordering[c] { def compare(a: c, b: c) = a.i compare b.i } } class containerofc(s: int)(implicit ordering: ordering[c]) { var internalcollection = new collection.mutable.treeset[c]() def +(c: c): containerofc = { this.internalcollection += c } def mkstringofelems() = { val y = this.internalcollection.tolist println(y.head.i) } }
scala collections types type-erasure
No comments:
Post a Comment