Pergunta

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()
Foi útil?

Solução

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)

Outras dicas

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
}
Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top