Canonical way for empty Array in Scala?

后端 未结 4 1330
名媛妹妹
名媛妹妹 2020-12-28 11:37

What is the canonical way to get an empty array in Scala? new Array[String](0) is too verbose.

4条回答
  •  一个人的身影
    2020-12-28 12:02

    Array() will be enough, most of the times. It will be of type Array[Nothing].

    If you use implicit conversions, you might need to actually write Array[Nothing], due to Bug #3474:

    def list[T](list: List[T]) = "foobar"
    implicit def array2list[T](array: Array[T]) = array.toList
    

    This will not work:

    list(Array()) => error: polymorphic expression cannot be instantiated to expected type;
        found   : [T]Array[T]
        required: List[?]
            list(Array())
                      ^
    

    This will:

    list(Array[Nothing]()) //Nothing ... any other type should work as well.
    

    But this is only a weird corner case of implicits. It's is quite possible that this problem will disappear in the future.

提交回复
热议问题