Search code examples
scalareflectionscala-macrospartialfunctionscala-compiler

How does the case by type work in scala?


I know about case classes, pattern matching, unapply and PartialFunction, but I'm confused about bellow macros snippet.

val declarations = weakTypeOf[T].declarations
val methods = declarations.collect { case m: MethodSymbol => m }

Scaladoc of MemberScope http://www.scala-lang.org/api/2.10.4/#scala.reflect.api.Scopes$MemberScope

Collect method accepts PartialFunction[Universe.Symbol, B] I can't find unapply method of MethodSymbol and it's also trait not a case class, so in witch code compiler transforms

{ case m: MethodSymbol => m }

Solution

  • Because MethodSymbol is not a generic type, the match

    case m: MethodSymbol => m
    

    is essentially equivalent to

    case m if m.isInstanceOf[MethodSymbol] => m
    

    There is absolutely no magic here, and unapply machinery is not related to such matches at all. Same thing can easily be done even in Java.