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

后端 未结 3 623
忘掉有多难
忘掉有多难 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条回答
  •  梦毁少年i
    2021-01-14 06:56

    Note that the Scala Array type is invariant. So Nothing being a subtype of everything may not be relevant.

    Also map and filter are not defined on Array. Implicit conversions in Predef are used to provide such methods for arrays.

    So the compiler is unable to find an implicit conversion from Array[Nothing] to something that has the map or filter defined. Using the REPL, I can actually see that such an implicit conversion should be available:

    scala> val conv = implicitly[Array[Nothing] <%< collection.mutable.ArrayOps[Nothing]]
    
    conv: <%<[Array[Nothing],scala.collection.mutable.ArrayOps[Nothing]] = 
    
    scala> conv(new Array[Nothing](5)).filter(_ => true)
    res8: Array[Nothing] = Array(null, null, null, null, null)
    

    So the question becomes why the compiler does not consider the genericArrayOps conversion.

提交回复
热议问题