使用Scala的宏来强制类型相等

时间:2013-02-21 04:08:03

标签: scala macros scala-2.10 scala-macros

我一直在尝试使用MacroParadise(herehere)以及其他一些新功能。今天在使用TypeTags时,我意识到我现在可以做这样的事情来强制实现类型相等。

def typeEq[A: TypeTag, B: TypeTag]: Boolean = {
    implicitly[TypeTag[A]].tpe =:= implicitly[TypeTag[B]].tpe
}

然后我记得TypeTag implicits是编译器生成的,我想我可以编写一个宏来实现更简洁的TypeTag用法,如下所示:

def foo[A](xs: List[A]): String = xs match {
  case y :: ys if typeEq[A, String] => y
  case y :: ys if typeEq[A, Int]    => y.toString 
} 

我在Lisp中只编写了一些宏,并且在尝试使用宏库时遇到了绊脚石。这导致我进行了多次尝试,但它们最终都扩展到Int =:= Int不起作用的东西,或像typeA =:= typeB这样两者都是免费的(这也是行不通的)。

这引出了两个问题:  1)如果没有foo上的上下文界限(如上所述),这是否可行?  2)如何正确地将由implicits获得的Type拼接到结果表达式中?

在我看来,宏和implicits应该允许我获取WeakTypeTag隐式并使用其tpe成员进行拼接,因为它们都发生在编译时。

1 个答案:

答案 0 :(得分:3)

您可以使用类型=:=[From,To]

强制执行类型相等
def bar[A,B](a:A,b:B)(implicit ev: A =:= B)= (a,b)

bar(1,1)
res0: (Int, Int) = (1,2)

bar(1,"3")

error: could not find implicit value for parameter ev: =:=[Int,java.lang.String]
       bar(1,"3")
          ^

修改

对不起,我猜你的问题有点不对劲。您的示例几乎可以正常工作,但编译器无法知道A是什么,因此无法找到TypeTag[A]的证据。如果添加绑定到方法定义的上下文,它将起作用:

def foo[A : TypeTag](xs: List[A]) = xs match {
  case _ if typeEq[A, String] => "yay"
  case _ => "noes"
}

scala> foo(List(2))
res0: String = noes

scala> foo(List(""))
res1: String = yay

<强> EDIT2

对于您的示例,您实际上根本不需要TypeTag,您可以使用模式匹配,因为您只使用第一个元素:

def foo[A](xs: List[A]): String = xs match {
  case (y: String) :: _ => y
  case y :: _ => y.toString
}

scala> foo(List(1,2,3))
res6: String = 1

scala> foo(List("foo"))
res7: String = foo

但请注意,模式计算并非详尽无遗,因为它无法处理Nil