简体   繁体   中英

How can I use a Java Optional object in Scala?

I have to use a Java function in Scala, which takes arguments of type Optional<Type> , and the object I have to pass to it also comes from a Java library but is simply of type Type . How can I use that in Scala?

Is it OK, If I typecast it like this. Note that here javaObj comes from a Java library and is of type Type . But someFunctionDefinedInAJavaLibrary function here expects an argument of type Optional<Type> .

import java.util.Optional
....
// javaObj here is of type Type and comes from a Java library
val scalaObj: Optional[Type] = javaObj.asInstanceOf[Optional[Type]]
// someFunctionDefinedInAJavaLibrary's argument is of type Optional<Type>
val r = someFunctionDefinedInAJavaLibrary(scalaObj)

It should be literally 1:1 the same expression as in Java:

someFunctionDefinedInAJavaLibrary(Optional.of(javaObj))

Just forget that asInstanceOf or scala.Option exist when invoking functions from your Java-API.


If you ever have to actually translate between Java's Optional and Scala's Option , you can use scala-java8-compat ( maven central ), but it's not necessary in this particular case, because there are no Option s anywhere.

Some("abc").asInstanceOf[Optional[String]] won't work because a Scala Option and a Java Optional are unrelated types.

You could include a Java8-compatibility library to convert between the types (just like the one for compatibility with Java collections that you may be familiar with), or just do it manually.

 def toJavaOptional[A](maybeA: Option[A]): Optional[A] = 
    maybeA.fold(Optional.empty)(a => Optional.of(a))

 def toScalaOption[A](maybeA: Optional[A]): Option[A] =
    if (maybeA.isEmpty) None else Some(maybeA.get)

javaObj is of type Type , not Optional<Type> , but the function expects Optional<Type>

Then do the same thing you would in Java (which does not automatically "box" a Type into Optional<Type> either):

callJavaFunction(Optional.of(a)) 

You can use all Java API methods in Scala directly, including Optional.of .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM