type mismatch error declaring list of classes

2019-09-04 07:14发布

问题:

  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
  }

Type type mismatch; found : List[(Any, Class[_ >: Int with NullPointerException with Thread with String])] required: List[(AnyRef, Class[_])]


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

Please suggest, what is wrong with Class[_]. Isn't it equivalent to Class[?] in java ? I appreciate, if you also suggest correct declaration for doing this..

回答1:

In Scala:

  • Any is the root of the Scala class.
  • AnyRef is the root of the class of reference types, it extends from Any.
  • AnyVal is the root class of all value types. it extends from Any
  • Null is a subtype of all reference types.
  • Nothingis a subtype of all other types including Null

So base on your code, you need to extend from Any, include AnyRef: reference types and AnyVal: 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
}