Created
May 21, 2015 10:44
-
-
Save diversit/57a7418d2a2762a061a3 to your computer and use it in GitHub Desktop.
Implicit Scala Option to Java Optional conversion
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* 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