How to access type companion object?

How to access the companion object of type? Especially useful for opaque types.

sample macro

import scala.quoted.*

transparent inline def companionOf[T]: Any = ${ companionOfImpl[T] }

def companionOfImpl[T: Type](using quotes: Quotes): Expr[Any] =
  import quotes.reflect.*
  val tpe = TypeRepr.of[T]
  val companion = tpe.typeSymbol.companionModule
  if companion.isNoSymbol then
    report.errorAndAbort(s"No companion object found for type ${tpe.show}")
  else Ref(companion).asExpr

sample usage

class A
object A

type B
object B


object Usage:
  companionOf[A]
  companionOf[B] // No companion object found for type main$package.B

Something like that? Better ctors and opaque types by MateuszKubuszok · Pull Request #181 · MateuszKubuszok/hearth · GitHub

1 Like

Yes, I think it answers my question. Thanks!