문제

Imagine I have a java list

val javaList: java.util.List[String] = null

If I wanted to use it as scala collection, let's say Buffer, I would simply add the following import (as described many times before)

import scala.collection.JavaConversions._

The problem is that I have to check if the list is different from null. This will not work:

javaList foreach println          //throws java.lang.NullPointerException

Is there a simple way to convert java list to scala collection in such a way, that null is converted to Buffer.empty? Something similar to Option factory:

Option(null)                      //> res0: Option[Null] = None
asScalaBuffer(javaList)           // I wish this to be ArrayBuffer()
도움이 되었습니까?

해결책

Just map it over and work with Option

Option(javaList).map(asScalaBuffer).getOrElse(ArrayBuffer.empty)

Update

If you still want a factory for null arrays/lists, then you can simulate it by a "constructor method" (basing on Rex Kerr's answer):

def ArrayBuffer[T](jl: JavaList[T]) = if (jl == null) ArrayBuffer.empty[T] else asScalaBuffer(jl)

and then use ArrayBuffer(null.asInstanceOf[JavaList[String]) it looks just like Option.apply:

def apply[A](x: A): Option[A] = if (x == null) None else Some(x)

다른 팁

You can always define your own:

import scala.collection.JavaConverters._
def safeScala[A](xs: java.util.List[A]) = {
  if (xs == null) collection.mutable.ArrayBuffer[A]()
  else xs.asScala
}
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top