tm: reflect.runtime.universe.Type =-6ren">
gpt4 book ai didi

scala - InstanceOf 来自运行时的某种类型,Scala

转载 作者:行者123 更新时间:2023-12-01 11:41:33 24 4
gpt4 key购买 nike

这个想法是,例如我们得到了一些对象的类型:

val tm = getTypeTag("String here").tpe
//> tm: reflect.runtime.universe.Type = java.lang.String

// for example I got another val or var, of some type:

val tmA: Any = "String here"
//> tmA: Any = String here

如何制作tmA.InstanceOf(tm)(是助记码)?因为 tm 它不是类型别名,我们不能准确地制作 InstanceOf[tm]

已编辑

我的意思是 asIstanceOf 的模拟函数,用于进行某种类型转换

EDITED2

我会自己部分回答我的问题。所以如果我们有 TypeTags 就很简单了!

def tGet[T](t: TypeTag[T], obj: Any): T = obj.asInstanceOf[T]

如果我们只得到 Type 而不是整个 TypeTag[T],情况就更难了。

最佳答案

您可以使用 mirror反射(reflect)实例:

val mirror = runtimeMirror(getClass.getClassLoader)

def isTm(a: Any) = mirror.reflect(a).symbol == tm.typeSymbol

然后:

scala> isTm("String here": Any)
res0: Boolean = true

scala> isTm(List("String here"): Any)
res1: Boolean = false

不过,我想我不必告诉你这是个多么糟糕的主意。

关于scala - InstanceOf 来自运行时的某种类型,Scala,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20045336/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com