scala - Type-specific functions for immutable generic classes -


say have container_generic[t] generic class , want specific functions available if t double example.

is there way without mutability or creating sub-classes?

the reason ask because sub-classes require lot of unnecessary code repetition. see example below:

class container_generic[t](x: seq[t]){   def map(f: t => t): container_generic[t] = new container_generic[t](x map f)   // def max: double = x.max //<-impossible implement unless t pre-specified }  class container_double_works(x: seq[double]) extends container_generic[double](x){   override def map(f: double => double): container_double_works = new container_double_works(x map f)   def max: double = x.max }  class container_double_doesntwork(x: seq[double]) extends container_generic[double](x){   def max: double = x.max }  // work val c_base = new container_generic[int](seq(1)).map(_*2) // : container_generic[int] val c_double = new container_double_works(seq(1)).map(_*2) // : container_double_works  // don't work correctly: no longer same class val c_double_doesntwork = new container_double_doesntwork(seq(1)).map(_*2) // : container_generic 

i still new scala, may taking wrong approach, or perhaps don't know correct term this.

you can everithing scala impicits

class container_generic[t](val x: seq[t]) {     def map(f: t => t): container_generic[t] = new container_generic[t](x map f) }  implicit class withmax(val c: container_generic[double]) {     def max: double = c.x.max }  val cdouble: container_generic[double] = new container_generic(seq(1.12)) val cstring: container_generic[string] = new container_generic(seq("12")) println(cdouble.max) //won't compile //  println(cstring.max) 

Comments

Popular posts from this blog

twig - Using Twigbridge in a Laravel 5.1 Package -

jdbc - Not able to establish database connection in eclipse -

firemonkey - How do I make a beep sound in Android using Delphi and the API? -