Canonical path for empty array in Scala?

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

+45
scala
Jun 22 2018-10-22
source share
3 answers
 Array[String]() 

You can leave the [String] part if it can be output (for example, methodThatAlwaysTakesAStringArray( Array() ) ).

+58
Jun 22 '10 at 14:18
source share
 val emptyArray = Array.empty[Type] 
+50
Jun 22 '10 at 18:17
source share

Array() will suffice in most cases. It will be of type Array[Nothing] .

If you use implicit conversions, you may need to write Array [Nothing] due to Error No. 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 just a strange angular case of implications. It is possible that this problem will disappear in the future.

+6
Jun 22 '10 at 17:41
source share



All Articles