Scala Implicit Type Conversion of Classes with Type Parameters -
i'm trying add functionality scala.collection.iterable trait, more specifically, printerate function iterates through elements , prints them out (to console if there no parameters, otherwise outputstream param). i'm using predefined extension method created object, printself(). however, causing compiler error, 'value printself not member of type parameter object.' i'd have separate file it's easy me use between several projects , applications.
here's current code conversion file:
import java.io.outputstream import scala.collection.iterable package conversion{ class convert { implicit def object2superobject(o:object) = new convertobject(o) implicit def iterable2superiterable[object](i:iterable[object]) = new convertiterable[object](i) } class convertobject(o:object){ def printself(){ println(o.tostring()) } def printself(os:outputstream){ os.write(o.tostring().getbytes()) } } class convertiterable[object](i:iterable[object]){ def printerate(){ i.foreach {x => x.printself() } } def printerate(os:outputstream){ i.foreach { x => x.printself(os) } } } }
i'm getting similar error in code that's trying test out, 'value printerate not member of scala.collection.immutable.range':
import conversion.convert package test { object program extends app { new testobj(10) test } class testobj(i: integer) { def test(){ val range = 0.until(i) 0.until(i).printerate() } } }
what's wrong way i'm approaching type conversion?
several things in fact:
- convert should object, not class.
- you use object instead of any
- you use object generic type identifier, instead of less confusing t.
- you not import implicit definitions (it's not enough import object itself).
this should work:
package conversion { object convert { implicit def object2superobject(o: any) = new convertobject(o) implicit def iterable2superiterable[t](i:iterable[t]) = new convertiterable[t](i) } class convertobject(o: any){ def printself(){ println(o.tostring()) } def printself(os:outputstream){ os.write(o.tostring().getbytes()) } } class convertiterable[t](i:iterable[t]){ import convert.object2superobject def printerate(){ i.foreach {x => x.printself() } } def printerate(os:outputstream){ i.foreach { x => x.printself(os) } } } } import conversion.convert._
second file:
package test { object program extends app { new testobj(10) test } class testobj(i: integer) { def test(){ val range = 0.until(i) 0.until(i).printerate() } } }
Comments
Post a Comment