Is there a way to instantiate an object from a generic in Scala 2?

35 Views Asked by At

Sorry for silly question in advance. I use Scala 2.12.15 and the design of the project implies the use of traits to add some logic to classes. I have class Printer and going to extend it with PrinterTrait to add soome logic. Is there a way to instantinate an object from generic, maybe using reflection API?

sealed abstract class Element(val value: String)
object Element {
    case object A extends Element(value = "a")
    case object B extends Element(value = "b")
    case object C extends Element(value = "c")
}

abstract class BasicClass {
    def print(): Unit
}

class Printer extends BasicClass {
    override def print(): Unit = {
        println("from Printer")
    }
}

trait PrinterTrait[E <: Element] extends Printer {

    val e: E = init
    
    def init: E = ???
    
    override def print(): Unit = {
        super.print()
        println(s"from Printer $e.value")
    }
    
}

And expexted result for

val p = new Printer with PrinterTrait[Element.A]
p.print()

is from Printer from Printer a

tried to play around with scala.reflect.runtime.universe but without success

0

There are 0 best solutions below