How to get a companion object from a type

I want to write a generic method and I need to get a companion object (especially a method apply

) from a type.

[update] X

is a case class, so the companion object has an apply method.

Example: def f[X]() = X.apply("42")

+3


source to share


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


Another solution which is much less, but you X, Y should be a case class



  case class X(s: String)
  case class Y(s: String)

  implicit def xConstruct = X
  implicit def yConstruct = Y

  def f[T](implicit construct: (String) => T) = construct("abc")

  println(f[X])
  println(f[Y])

      

+1


source







All Articles