Scala - 使用案例类尝试获取 TypeTag 时没有可用的 TypeTag 异常? [英] Scala - No TypeTag Available Exception when using case class to try to get TypeTag?

查看:51
本文介绍了Scala - 使用案例类尝试获取 TypeTag 时没有可用的 TypeTag 异常?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在查看 scala 反射 API,但我收到了很多异常.

I'm looking at the scala reflect API and I'm getting lots of exceptions.

文档参考:http://docs.scala-lang.org/overviews/reflection/environment-universes-mirrors.html

如何从泛型中获取 typetag?

How do I get the typetag from a generic?

  def getChildSettings[T: ru.TypeTag](path: String, settingsParameterObject: T) = {

    import scala.reflect.runtime.{ currentMirror => m }

    val m = ru.runtimeMirror(getClass.getClassLoader)
    val classC = ru.typeOf[T].typeSymbol.asClass
}

我得到一个例外:

No TypeTag available for ParameterObject.type

即使是一个非常简单的例子似乎也不起作用(编辑是的,它在 repl 中起作用)

Even a very simple example doesn't seem to work (edit yes it does in the repl)

import scala.reflect.runtime.universe._
import scala.reflect.runtime.currentMirror
import scala.reflect.runtime.{universe => ru}

def getTypeTag[T: ru.TypeTag](obj: T) = ru.typeTag[T]

case class ParameterObject(stringType: String, optionType: Option[String])

getTypeTag(ParameterObject)

我猜这与我调用方法的方式有关.

I'm guessing it's something about how I'm invoking the method.

推荐答案

我终于找到了问题所在.案例类必须在顶级定义 - 它们不能嵌套.这样的事情会失败.

I finally found out what the issue was. The case classes must be defined top level - they cannot be nested. Something like this would fail.

class Foo {
  describe("getSettings") {
    case class ParameterObject(foo: String)
    settings.getTypeTag(path, ParameterObject)
  }
}

class Clazzy {
      def getTypeTag[T: TypeTag](obj: T) = ru.typeTag[T]
}

这篇关于Scala - 使用案例类尝试获取 TypeTag 时没有可用的 TypeTag 异常?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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