可以在类中定义Scala宏(作为该类的方法)吗?

时间:2016-03-23 21:54:44

标签: scala macros scala-macros scala-quasiquotes reify

我的Scala断言库需要Scala宏(reify,quasiquote,macro impl)。

我希望能够做到这一点:

object1.assertEquals(object2) // success: object1 = object2

或者像这样:

3.assertEquals(1 + 1) // failure: 1 + 1 /= 3 

可以在隐式类中定义Scala宏吗?

2 个答案:

答案 0 :(得分:1)

// ed:写包

package so

trait AssertEquals[T, V] {
  def assertEquals(t: T, v: V): Boolean
}

object AssertEquals {
  implicit def assertEquals[T, V]: AssertEquals[T, V] = macro impl[T, V]


  implicit class WithAssertEquals[T](t: T) {
    def assertEquals[V](v: V)(implicit assertEquals: AssertEquals[T, V]): Boolean = assertEquals.assertEquals(t, v)
  }

  def impl[T: c.WeakTypeTag, V: c.WeakTypeTag](c: Context) = {
    import c.universe._
    val _t = c.weakTypeOf[T]
    val _v = c.weakTypeOf[V]

    //edit 2 : use symbolOf instead typeOf
    q"""
      {
      new ${symbolOf[so.AssertEquals[_, _]]}[${_t},${_v}]{
        def assertEquals(t: ${_t}, v: ${_v}): Boolean = t == v
      }
      }
      """
  }
}

// test

import AssertEquals.WithAssertEquals

assert(1.assertEquals(2) == false)
assert(2.assertEquals(2) == true)
assert("a".assertEquals("a") == true)
assert("a".assertEquals("b") == false)
assert("a".assertEquals(1) == false)

答案 1 :(得分:0)

实现必须在对象或宏包中,但宏实现的方法可以在隐式类中。 注意获取对隐式类包装的对象的引用所需的val self = q"${c.prefix}.self"

import scala.language.experimental.macros
import scala.reflect.macros.blackbox.Context


object assertions {
  implicit class AssertEquals[T](val self: T) extends AnyVal {
    def assertEquals(other: T): Unit = macro AssertionMacros.assertEquals[T]
  }

  object AssertionMacros {
    def assertEquals[T](c: Context)(other: c.Tree): c.Tree = {
      import c.universe._
      val self = q"${c.prefix}.self"
      q"_root_.scala.Predef.assert($self == $other)"
    }
  }
}

用法:

scala> import assertions._
import assertions._

scala> "foo" assertEquals "foo"

scala> "foo" assertEquals "bar"
java.lang.AssertionError: assertion failed
  at scala.Predef$.assert(Predef.scala:151)
  ... 43 elided