Why does map/filter … not work with an Array of Nothing?

后端 未结 3 615
忘掉有多难
忘掉有多难 2021-01-14 06:39

Isn\'t Nothing a subtype of all types?

scala> val array = new Array(5)
array: Array[Nothing] = Array(null, null, null, null, null)

scala> array.map(_          


        
3条回答
  •  攒了一身酷
    2021-01-14 06:57

    I suspect Scala shouldn't let you do that kind of Array[Nothing] instantiation. There are by definition no instances of nothing around, yet your array looks like it's filled with Nothings that are null, but null is not a valid value for Nothing. This for instance fails with the error type mismatch; found : Null(null) required: Nothing

    val n: Nothing = null
    

    So I'd expect to run into trouble each time you can actually fool the system to believe you are finally getting hold of a much sought for instance of Nothing

    Here's another weird case. Run this:

    object Main {
    
      class Parametrized[T] { var value: T = _ }
    
      def main(args: Array[String]) {
        val p = new Parametrized // typed as Parametrized[Nothing]
        val n = p.value  // n is now actually an instance of Nothing... isn't it?
        println(p.value) // prints null, but null is not an instance of Nothing
        println(n)       // throws NullPointerException...
      }
    
    }
    

提交回复
热议问题