Instanciate concrete class a generic method in scala -


i have generic method generic type parameter t subclass of myclass. inside method, want create e new instance of t, how can that?

this doesn't work (because of type erasure):

object demo extends app {   def mymethod[t <: myclass](): unit = {       val t = new t // gives error: class type required t found    }   mymethod[mysubclassa]() }   abstract class myclass class mysubclassa extends myclass class mysubclassb extends myclass 

it fails work, not (primarily) because of type erasure, because definition should make sense t satisfy type bounds, , new t doesn't. e.g. t can myclass or abstract subclass, or subclass without parameter-less constructor, or trait (traits can extend classes), or...

if runtime error enough, can go sergey lagutin's solution. more reasonable cases pass way create t mymethod. possibly implicit argument, e.g.

class factory[t](f: () => t) {   def make(): t = f() } object factory {   implicit val mysubclassafactory =      new factory(() => new mysubclassa)    implicit val mysubclassbfactory =      new factory(() => new mysubclassb) } def mymethod[t <: myclass](implicit factory: factory[t]): unit = {   val t = factory.make()   ... }  mymethod[mysubclassa] // works mymethod[myclass] // compilation error mymethod[asubclassforwhichfactoryisnotdefined] // compilation error 

Comments