Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Test if implicit exists

Tags:

macros

scala

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
  }

 }
like image 345
Oleg Avatar asked Jan 28 '26 15:01

Oleg


1 Answers

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(…)"
}
like image 55
devkat Avatar answered Jan 31 '26 20:01

devkat



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!