简体   繁体   English

模式匹配语法可替代Scala宏中_ =:= typeOf [_]测试链

[英]Pattern matching syntax alternative to chains of _=:=typeOf[_] tests in Scala macros

Is there already a pattern match alternative for writing long winded tests like 是否已经有一种模式匹配替代方法可以编写冗长的测试,例如

if (aTpe =:= typeOf[Int]) 1
else if (aTpe =:= typeOf[Long]) 2
else if (aTpe =:= typeOf[Double]) 3
else ...

perhaps something that looks a little like 也许看起来有点像

aTpe match {
  case tpe[Int] => 1
  case tpe[Long] => 2
  case tpe[Doble] => 3
  ...
}

It looks pretty easy to write an extractor for this, but I want to find out if there isn't already something like this. 为此编写一个提取器看起来很容易,但是我想知道是否还没有这样的东西。

What I've been doing in normal code so far is materialized types. 到目前为止,我在普通代码中一直在做的是物化类型。 I guess it could be used in macros as well: 我猜它也可以在宏中使用:

val ClassOfInt = classOf[Int]
val ClassOfLong = classOf[Long]

aTpe match {
   case ClassOfInt => 1
   case ClassOfLong => 2
}

It works but I'd very much like to know if there's a 'terser' way of doing so. 它可以工作,但是我非常想知道是否有一种“更短的”方式。

Of course it is possible to write your if-else-chain nearly the same way with a pattern match and guards: 当然,可以使用模式匹配和保护以几乎相同的方式编写if-else-chain:

scala> import scala.reflect.runtime.universe._
import scala.reflect.runtime.universe._

scala> def f[A : TypeTag] = typeOf[A] match {
    case t if t =:= typeOf[Int] => 1
    case t if t =:= typeOf[Long] => 2
    case _ => 0
  }
f: [A](implicit evidence$1: reflect.runtime.universe.TypeTag[A])Int

scala> f[Int]
res5: Int = 1

scala> f[String]
res6: Int = 0

However a construct like case tpe[Int] => as shown in your question is not possible because of this ticket: SI-884 - it is just an unimplemented feature. 但是,由于此票证,因此无法像问题中所示的case tpe[Int] =>那样构造case tpe[Int] =>SI-884-这只是一个未实现的功能。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM