development

Scala에서 빈 배열에 대한 정식 방법?

big-blog 2020. 12. 3. 08:06
반응형

Scala에서 빈 배열에 대한 정식 방법?


Scala에서 빈 배열을 얻는 표준 방법은 무엇입니까? new Array[String](0)너무 장황합니다.


Array[String]()

[String]추론 할 수있는 경우 부품을 생략 할 수 있습니다 (예 :) methodThatAlwaysTakesAStringArray( Array() ).


val emptyArray =  Array.empty[Type]

Array()대부분의 경우 충분합니다. 유형이 Array[Nothing]됩니다.

암시 적 변환을 사용하는 경우 Bug # 3474 로 인해 실제로 Array [Nothing]을 작성해야 할 수 있습니다 .

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

작동하지 않습니다.

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

이것은 :

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

그러나 이것은 암묵적인 경우에 불과합니다. 이 문제는 앞으로 사라질 가능성이 높습니다.


배열 유형이 기본 요소 중 하나 인 경우 scala.Array의 단축키를 사용할 수 있습니다.

예를 들어 바이트 배열의 경우 다음과 같습니다.

val arr = Array.emptyByteArray

유형을 추론 할 수없고 덜 장황하게 유지하려는 경우에 유용합니다.

참고 URL : https://stackoverflow.com/questions/3093973/canonical-way-for-empty-array-in-scala

반응형