In my Scala code I need to interact with Java libraries.
The method I want to use expects parameter of type List<java.util.Long>
, but I have Scala type Option[List[Long]]
. The problem I faced is that I need manually apply Predef.long2Long
function to convert from Scala Long
to java.util.Long
:
val userIds = Option(List(1,2,3,4))
val methodParameter = userIds.map(list => list.map(long2Long).asJava).orNull
is there some way to convert this list in more elegant and concise way?
EDIT: I can even simplify question: how to convert Option[scala.Boolean]
to java.util.Boolean
? Here I need to do same:
isUsed.map(isUsedVal => boolean2Boolean(isUsedVal)).orNull,
For the List[Long]
:
import scala.collection.JavaConverters._
val l = List(1L,2L,3L,4L)
l.map(java.lang.Long.valueOf).asJava
// or
l.map(_.asInstanceOf[AnyRef]).asJava
// or
l.map(Long.box).asJava
For the Option[Boolean]
:
val mb = Some(true)
mb.map(java.lang.Boolean.valueOf).orNull
// or
mb.map(_.asInstanceOf[AnyRef]).orNull
// or
mb.map(Boolean.box).orNull
Can you use JavaConverters ? and do something like that
val sl = new scala.collection.mutable.ListBuffer[Int]
val jl : java.util.List[Int] = sl.asJava
It's worth mentioning that long2Long
and boolean2Boolean
are implicit, but that doesn't help you much to make this more elegant or clear, I think. It does allow you to things like:
type JB = java.lang.Boolean
isUsed.fold(null : JB)(implicitly)
//Or:
isUsed.map { b => b : JB }.orNull
//Or even:
isUsed.map[JB](identity).orNull
But that's not particularly readable, in my opinion.
These sorts of methods are perfect candidates for an implicit class method. You can enrich your classes with these methods so that you only have to write the tedious or inelegant code once. For example, you might consider:
object MoreJavaConversions {
import scala.collection.JavaConverters._
implicit class RichListLong(val list: Option[List[Long]]) extends AnyVal {
def asJava : java.util.List[java.lang.Long] = list.map(_.map(long2Long).asJava).orNull
}
implicit class RichOptionBoolean(val bool: Option[Boolean]) extends AnyVal {
def asJava : java.lang.Boolean = bool.map(boolean2Boolean).orNull
}
}
Which would later allow you to do:
import MoreJavaConversions._
val myUsers = Option(List(1l, 2l, 3l))
myUsers.asJava //java.util.List[java.lang.Long]
Option(true).asJava //java.lang.Boolean
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With