Oleg Golovanov Oleg Golovanov - 3 months ago 13
Scala Question

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
}

}

Answer

It should be possible to use inferImplicitValue:

c.inferImplicitValue(typeOf[Packer[tpe.type]]) match {
  case EmptyTree => … // default conversion
  case packer => q"packer.pack(…)"
}
Comments