【问题标题】:List of case classes doesn't match T <: Serializable案例类列表不匹配 T <: Serializable
【发布时间】:2018-05-11 21:22:53
【问题描述】:

给定一个类型定义T &lt;: Serializable,为什么它不匹配所有可序列化的东西,包括可序列化实例的列表?

即给定:

case class Bar()

def foo[T <: Serializable](param1: T) = println(param1)

foo(Bar())
foo(List(Bar()))

编译器给出以下错误:

Error:(6, 2) inferred type arguments [List[A$A15.this.Bar]] do not conform to method foo's type parameter bounds [T <: Serializable]

case 类扩展了 SerializableList 也是如此 - 为什么 Bars 列表与类型不匹配?

【问题讨论】:

    标签: scala serialization


    【解决方案1】:

    案例类扩展SerializableList也是如此

    这仅适用于 Scala 2.12.x (https://issues.scala-lang.org/browse/SI-7402)。之前的版本(2.11 和 2.10)在 List 上没有 Serializable 特征。如果您使用 2.12,您的代码将按预期编译。

    下面的答案考虑了之前的版本实现:


    List[T] 不扩展可序列化,它派生::Nil 做。显式使用::.apply时可以看到这一点

    foo(::(1, Nil))
    

    因为推断的类型是::(或缺点),所以可以编译。相反:

    foo(1 :: Nil)
    

    不是因为List 上的:: 方法返回List[A],而不是::

    另一件事是List.apply 始终是运行时::Nil(因为List 是抽象的),这就是诸如以下测试的原因:

    List(1,2,3).isInstanceOf[Serializable]
    

    产量true。如果我们检查底层运行时类,我们会看到:

    List(1, 2, 3).getClass.getName
    

    产量

    scala.collection.immutable.$colon$colon
    

    【讨论】:

    • 好吧,现在我因为没有检查正确的文档而感到愚蠢-谢谢!我确实在使用 Scala 2.11 :)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-04-24
    • 1970-01-01
    • 1970-01-01
    • 2020-02-13
    • 1970-01-01
    • 2017-02-25
    • 2019-03-09
    相关资源
    最近更新 更多