How to get a companion object from a type
2 answers
There is no general solution, nor is there anything restricting the companion object to apply the method. It can be a companion with no application. I would suggest using the type type template in this case.
trait CompanionWithApply[T] {
def apply(s: String): T
}
class X(s: String)
object X extends CompanionWithApply[X] {
def apply(s: String): X = new X(s)
}
class Y(s: String)
object Y extends CompanionWithApply[Y]{
def apply(s: String): Y = new Y(s)
}
implicit val XCompanion = X
implicit val YCompanion = Y
def f[T: CompanionWithApply] = implicitly[CompanionWithApply[T]].apply("42")
println(f[X])
println(f[Y])
+2
source to share