java - Scala - Extending a reference type without subclassing it -
i have java class subclass. subclass add together convenience methods - done using external methods, because @ public fields, , don't modify anything.
if base of operations class value type, i'd utilize value wrappers - extends anyval
. base of operations class java reference type. there improve way subclass other extending it?
to address sec paragraph specifically, type wrap value class can reference type , still avoid object allocation involved in wrapping. example, if you've got these implicit classes:
implicit class myint(val underlying: int) extends anyval { def inc: int = underlying + 1 } implicit class mystring(val underlying: string) extends anyval { def firstchar: char = underlying.charat(0) } implicit class mynonvalueclassstring(val underlying: string) { def firstcharnonvalueclass: char = underlying.charat(0) }
and code uses them:
println(42.inc) println("hello".firstchar) println("hello".firstcharnonvalueclass)
you can compile -xprint:flatten
see desugared version (reformatted here clarity):
scala.this.predef.println( scala.int.box(demo$myint.this.inc$extension(demo.this.myint(42))) ); scala.this.predef.println( scala.char.box( demo$mystring.this.firstchar$extension(demo.this.mystring("hello")) ) ); scala.this.predef.println( scala.char.box( demo.this.mynonvalueclassstring("hello").firstcharnonvalueclass() ) );
as can see, firstchar
phone call doesn't involve new object.
java scala
No comments:
Post a Comment