'How to return subtype of a generic trait in scala?

I am trying to create a factory pattern, and the return type is a parametrized trait, and the actual return type will be a subtype of that trait, but I do not know the generic type beforehand, so I don't know how to specify the return type. A simplified version is like this:

trait Mapper[T] {
    def createMap(a: T, b: T): T
}

class MapperA extends Mapper[String]{
    override def createMap(a: String, b: String): String = {
        a + b
    }
}

class MapperB extends Mapper[Int]{
    override def createMap(a: Int, b: Int): Int = {
        a + b + b + b
    }
}

def factory(typeOfMapper: String): Mapper = {
    typeOfMapper match {
        case "mapperA" => new MapperA()
        case "mapperB" => new MapperB()
    }
}

val mapper = factory("mapperA")

This will give me and error of

trait Mapper takes type parameters

but I do not know the generic type beforehand. What should the return type be for the factory method here?



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source