Skip to content

Instantly share code, notes, and snippets.

@diversit
Created May 21, 2015 10:44
Show Gist options
  • Save diversit/57a7418d2a2762a061a3 to your computer and use it in GitHub Desktop.
Save diversit/57a7418d2a2762a061a3 to your computer and use it in GitHub Desktop.
Implicit Scala Option to Java Optional conversion
/**
* Convers any type A to a Java compatible type B if such a conversion exists.
* Default they exist for all primitive types.
*
* Usage: Option(1).asJava[java.lang.Integer]
*
* The type [B] must be provided because the compiler is aparently not able to determine the wanted java.util.Optional<B> type
* since that type is removed due to type erasure.
* If you want to keep the type A just do not provide a type B when using ```asJava```. For example for custom Pojos.
*/
object ScalaToJava {
implicit class OptionToOptional[A](val o: Option[A]) extends AnyVal {
import java.util.Optional
def asJava[B](implicit conv: A => B): Optional[B] = o map (value => Optional.of(conv(value))) getOrElse Optional.empty()
}
}
/**
* This test uses some of our Java types to test the implicit conversion.
*/
object ScalaToJavaTest extends App {
val b: scala.Boolean = true
val f: scala.Float = 1f
new LightXY(Optional.of(java.lang.Boolean.valueOf(b)), Optional.of(java.lang.Float.valueOf(f)))
val c = Color.fromXY(1,1)
import Tmp._
val l1 = new LightXY(None.asJava[java.lang.Boolean], Some(f).asJava[java.lang.Float])
println(l1)
val l2 = new LightXY(Some(b).asJava[java.lang.Boolean], Some(f).asJava[java.lang.Float], Some(c).asJava)
println(l2)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment