Scala:通过reflect.runtime.universe.Type 进行模式匹配? [英] Scala: pattern matching over a reflect.runtime.universe.Type?

查看:28
本文介绍了Scala:通过reflect.runtime.universe.Type 进行模式匹配?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何对reflect.runtime.universe.Type 进行模式匹配?

how can I do a pattern match over a reflect.runtime.universe.Type?

def test(t: reflect.runtime.universe.Type) {
  t match {
    case Int => \\ ...
    case Double => \\ ...
    case String => \\ ... 
    case _ =>  \\ ...
  }
}    

这不起作用,因为口译员抱怨:

This dosn't work, as the interpreter complains:

error: pattern type is incompatible with expected type;
 found   : Int.type
 required: reflect.runtime.universe.Type
Note: if you intended to match against the class, try `case _: Int`
         case Int => // ...
              ^

尝试该建议也不起作用:

Trying the suggestion does not work either:

def test(t: reflect.runtime.universe.Type) {
  t match {
    case _: Int => \\ ...
    case _: Double => \\ ...
    case _: String => \\ ... 
    case _ =>  \\ ...
  }
}    

...

error: pattern type is incompatible with expected type;
 found   : Int
 required: reflect.runtime.universe.TypeApi
            case _: Int => // ...
                 ^

那么正确的语法是什么?

So what is the correct syntax for this?

谢谢!

推荐答案

TypeTag API 有一个比较运算符 =:= 和获取 的方法键入 给定类的实例,您可以将它们与守卫结合以获得所需的结果:

The TypeTag API has a comparison operator =:= and a method for obtaining the Type instance for a given class, you can combine these with guards to obtain the desired result:

import scala.reflect.runtime.universe._

def test(t: Type) {
  t match {
    case t if t =:= typeOf[Int] => println("int")
    case t if t =:= typeOf[String] => println("string")
    case _ =>  
  }
} 

这篇关于Scala:通过reflect.runtime.universe.Type 进行模式匹配?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆