Oleg
Oleg

Reputation: 3210

Test if implicit exists

Is it possible on compile time using macros to test if exists some implicit for current type ?

something like this

def packOne(tpe:c.universe.Type,....) = {
  if(tpe =:= ByteTpe ) makeast1
  else if (tpe =:= LongTpe ) makeast2
  else if (tpe =:= c.typeOf[java.lang.String]) makeast3
  ....
  else exists implicit convention for TPE { 
  q"""
  // call some function with implicit PACK[T]
   implicitly[Packer[$tpe]].pack(...)
  """
  } else {
  // Make default conversion
  }

 }

Upvotes: 3

Views: 395

Answers (1)

devkat
devkat

Reputation: 1644

It should be possible to use inferImplicitValue:

val t = c.internal.typeRef(NoPrefix, typeOf[Packer[_]].typeSymbol, List(tpe))
c.inferImplicitValue(t) match {
  case EmptyTree => … // default conversion
  case packer => q"packer.pack(…)"
}

Upvotes: 2

Related Questions