【问题标题】:Passing type information to function in Scala将类型信息传递给 Scala 中的函数
【发布时间】:2011-12-01 00:40:07
【问题描述】:

我有对 json 对象执行一些常见操作的代码,即提取。所以我想创建一个接受类型参数的泛型函数,代码如下所示:

def getMessageType[T](json: JValue): Either[GenericError,T] = {
  try {
    Right(json.extract[T])
  } catch {
    case e: MappingException => jsonToError(json)
  }
}

问题是如何将 T 信息传递给该函数?

【问题讨论】:

    标签: function scala types


    【解决方案1】:

    如果你查看the definition of extract: 你会发现它需要一个 Manifest 隐含:

    def extract[A](json: JValue)
        (implicit formats: Formats, mf: Manifest[A]): A
    

    这通过将“类型”作为值来绕过 JVM 类型擦除。为您 案例,我认为你应该做同样的事情:

    def getMessageType[T](json: JValue)
        (implicit f: Formats, mf: Manifest[T]): T =
    {
        json.extract[T]
    }
    

    这个:

    1. 为您的方法提供隐式参数,这些参数必须由调用者完成。

    2. 创建(相同的)隐式参数以将它们传递给extract。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-10-23
      • 1970-01-01
      • 1970-01-01
      • 2021-09-04
      • 2013-10-19
      • 2019-06-19
      • 1970-01-01
      相关资源
      最近更新 更多