Search code examples
scalacompanion-object

Ensure that parametric type has companion object


I'd like to do something like this (and please, don't ask why):

trait A[T /* tell that there exists companion for T */] {
    def f = T.g
}

Is it possible to achieve this?


Solution

  • It's not possible out of the box. You'll have to use a macro based solution. I happen to have published a gist of such a solution a while ago.

    You could use it like this:

    def getCompanion[T: HasCompanion] = HasCompanion[T].companion
    

    However you can't use context bounds on the type parameter of a trait.