【问题标题】:type mismatch error declaring list of classes类型不匹配错误声明类列表
【发布时间】:2015-10-17 04:27:50
【问题描述】:
  def getValueAndItsType() : List[ (AnyRef, Class[_]) ] = {
    val dataSet1 = ("some string data", classOf[String])
    val dataSet2 = (new Thread(), classOf[Thread])
    val dataSet3 = (new NullPointerException(), classOf[NullPointerException])
    val dataSet4 = (5, classOf[Int])
    val list = List(dataSet1, dataSet2, dataSet3, dataSet4)
    list
  }

类型类型不匹配;成立 : List[(Any, Class[_ >: Int with NullPointerException with Thread with String])] 必需:List[(AnyRef, Class[_])]


If dataSet4 is removed from List, the compile time error disappears

请提出建议,Class[_] 有什么问题。是不是 相当于 java 中的 Class[?] ?我很感激,如果你也建议 这样做的正确声明..

【问题讨论】:

    标签: list scala generics collections


    【解决方案1】:

    Scala 中:

    • AnyScala 类的根。
    • AnyRef引用类型类的根,它继承自Any
    • AnyVal 是所有值类型的根类。它从Any延伸
    • Null 是所有引用类型的子类型。
    • Nothing所有其他类型的子类型,包括Null

    所以根据你的代码,你需要从Any扩展,包括AnyRef: reference typesAnyVal: values types

    def getValueAndItsType() : List[ (Any, _ <: Any) ] = {
        val dataSet1 = ("some string data", classOf[String])
        val dataSet2 = (new Thread(), classOf[Thread])
        val dataSet3 = (new NullPointerException(), classOf[NullPointerException])
        val list = List(dataSet1, dataSet2, dataSet3)
        list
    }
    

    【讨论】:

    • 感谢您的快速回复。我刚刚更新了问题,因为它不接受包含 Int 类型的 dataSet4。
    • 我想,scala 中的任何东西都是对象。谢谢你的回答:)
    • @rits 是的,你是对的,scala 中的任何东西都是对象,Any 是根类。
    猜你喜欢
    • 2012-09-02
    • 1970-01-01
    • 2014-11-10
    • 1970-01-01
    • 1970-01-01
    • 2010-12-09
    • 2013-01-16
    • 2015-02-24
    相关资源
    最近更新 更多