Scala 中空数组的规范方法?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3093973/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-22 02:14:58  来源:igfitidea点击:

Canonical way for empty Array in Scala?

scala

提问by Landon Kuhn

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

在 Scala 中获取空数组的规范方法是什么?new Array[String](0)太冗长了。

回答by sepp2k

Array[String]()

You can leave out the [String]part if it can be inferred (e.g. methodThatAlwaysTakesAStringArray( Array() )).

[String]如果可以推断出该部分,您可以省略它(例如methodThatAlwaysTakesAStringArray( Array() ))。

回答by Eastsun

val emptyArray =  Array.empty[Type]

回答by soc

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

Array()大多数时候就足够了。它将是 类型Array[Nothing]

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

如果您使用隐式转换,您可能需要实际编写 Array[Nothing],由于错误 #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.

但这只是隐式的一个奇怪的极端情况。这个问题很有可能在未来消失。

回答by galbarm

If the array type is one of the primitives, you can use the shortcuts from scala.Array.

如果数组类型是原语之一,则可以使用 scala.Array 中的快捷方式。

For example for a byte array it would be:

例如对于字节数组,它将是:

val arr = Array.emptyByteArray

This is useful when the type cannot be inferred and you want to remain less verbose.

当无法推断类型并且您希望保持不那么冗长时,这很有用。