3

Suppose I want a macro that takes an expression and returns the arity if it's a tuple literal. Something like this works for tuples but returns Some(1) instead of None for everything else:

import scala.reflect.macros.blackbox.Context

class ArityMacros(val c: Context) {
  import c.universe._

  def arity[A: c.WeakTypeTag](a: c.Expr[A]): c.Tree = a.tree match {
    case q"(..$xs)" => q"_root_.scala.Some(${ xs.size })"
    case _ => q"_root_.scala.None"
  }
}

import scala.language.experimental.macros

def arity[A](a: A): Option[Int] = macro ArityMacros.arity[A]

I know I can do something like this:

class ArityMacros(val c: Context) {
  import c.universe._

  def arity[A: c.WeakTypeTag](a: c.Expr[A]): c.Tree = a.tree match {
    case q"scala.Tuple1.apply[$_]($_)" => q"_root_.scala.Some(1)"
    case q"(..$xs)" if xs.size > 1     => q"_root_.scala.Some(${ xs.size })"
    case other                         => q"_root_.scala.None"
  }
}

But feel like there should be a nicer way to distinguish the Tuple1 and non-tuple cases (and maybe that I've used it in the past?).

Travis Brown
  • 138,631
  • 12
  • 375
  • 680

0 Answers0