I am trying to create a generic method to create class instance by specified type parameter.
Code change conditions: * as minimum as possible changes to P1 - P3 classes its a legacy code an code below is just a prototype, ideally no changes at all to these classes.
See my code below.
trait P {
def run() : Unit = ???
}
class P1 (cfg : String ) extends P {
override def run() : Unit = {
println("1")
}
}
class P2 (cfg : String )extends P {
override def run() : Unit = {
println("2")
}
}
class P3 (cfg : String ) extends P {
override def run() : Unit = {
println("3")
}
}
def executor[T <: P](cfg: String): Unit = {
new T(cfg).run()
}
executor[P1]("someCfg")
executor[P2]("someCfg")
executor[P3]("someCfg")
Here is error I am getting:
Error:(26, 10) class type required but T found
new T(cfg).run()
^
Error:(53, 10) class type required but T found
new T(cfg).run()
^
def executor[T<:P](cfg: String)(fn: String => T): Unit = fn(cfg).run(). And then use it likeexecutor("someCfg")(new P1(_)).