【问题标题】:How to use anonymous types when Manifest type is required需要 Manifest 类型时如何使用匿名类型
【发布时间】:2014-05-15 18:41:15
【问题描述】:

我不熟悉 Manifest 类型。 Jackson 库使用这种类型,即在 ObjectMapper 中。所以给定这个方法:

def fromJson[T: Manifest](jsonInputStream: InputStream): T

我尝试使用匿名类型来调用它,例如:

....fromJson[{val numRounds: Int; val numSeconds: Int }](json)

但我得到一个编译错误。

[error]  found   : scala.reflect.Manifest[Object]
[error]  required: Manifest[AnyRef{val numRounds: Int; val numSeconds: Int}]
[error] Note: Object >: AnyRef{val numRounds: Int; val numSeconds: Int}, but trait Manifest is invariant in type T.
[error] You may wish to investigate a wildcard type such as `_ >: AnyRef{val numRounds: Int; val numSeconds: Int}`. (SLS 3.2.10)
[error]           val d = jsonParser.fromJson[{val numRounds: Int; val numSeconds: Int}](json)

有人可以在这里解释这个问题吗?我真的必须为该类型创建一个适当的类吗?

【问题讨论】:

    标签: scala


    【解决方案1】:

    我已经在Manifest error for anonymous type 中回答了你的问题:

    Looks like 清单是不可能的。你应该使用 TypeTag 代替。像这样:

    import scala.reflect.runtime.universe._
    object GenericSerializer
    {
      def apply[T <:AnyRef]()(implicit tag: TypeTag[T]) = {}
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-01-30
      相关资源
      最近更新 更多