Is there a way to determine whether a method in a trait has a default implementation? #17376
-
| 
         Is there a way to determine whether a method in a trait has a default implementation? // ThisBuild / scalaVersion := "3.3.0-RC4"
// Macro.scala
import scala.quoted.*
object Macro {
  inline def m[T]: String = ${ impl[T] }
  def impl[T](using Quotes, Type[T]): Expr[String] = {
    import quotes.reflect.*
    def hasImpl(declaration: Symbol): Boolean = declaration.tree match
      case defdef: DefDef => defdef.rhs.isDefined
      case _              => false
    Expr(
      TypeRepr
        .of[T]
        .typeSymbol
        .declarations
        .map { d =>
          (d.name, hasImpl(d))
        }
        .toString
    )
  }
}
// Main.scala
trait TestTrait {
    def defaultImpl: Int = 1
    def method: Int
}
@main
def main() = {
    // expected: List((<init>,false), (defaultImpl,true), (method,false))
    // actual: List((<init>,false), (defaultImpl,false), (method,false))
    println(Macro.m[TestTrait])
} | 
  
Beta Was this translation helpful? Give feedback.
      
      
          Answered by
          
            cacapouh
          
      
      
        Apr 30, 2023 
      
    
    Replies: 1 comment
-
| 
         I found that by checking the flags, we can determine whether an implementation exists or not.  | 
  
Beta Was this translation helpful? Give feedback.
                  
                    0 replies
                  
                
            
      Answer selected by
        cacapouh
  
    Sign up for free
    to join this conversation on GitHub.
    Already have an account?
    Sign in to comment
  
        
    
I found that by checking the flags, we can determine whether an implementation exists or not.