I am writing a small JavaFx application in Scala and I like to use RxScala and RxJavaFx for this. With the following code I get a RxJava Observable
:
JavaFxObservable.fromObservableValue(textfield.textProperty())
Obviously, as I write in Scala, I would like to have a RxScala Observable
instead. Now I found this post, saying that I either have to import the implicit conversion class JavaConversions._
or call toScalaObservable
directly. However, the first option doesn't do it for me and the second option looks kind of ugly:
Option 1:
import rx.lang.scala.JavaConversions._
JavaFxObservable.fromObservableValue(textfield.textProperty())
.map(s => /* do something */)
This doesn't work, as RxJava offers a map
operator as well, although the type of the argument is technically speaking different.
Option 2:
import rx.lang.scala.JavaConversions._
toScalaObservable(JavaFxObservable.fromObservableValue(textfield.textProperty()))
.map(s => /* do something */)
This works, but be honest people, this looks just really horrible!
Question 1: Am I missing something or are these really the only two options?
I mean, to convert from Java's standard collections to Scala's collections (and vise versa) you got two option: JavaConverters
and JavaConversions
. The former introduces a keyword asJava
/asScala
, whereas the latter is kind of equivalent to rx.lang.scala.JavaConversions
and does the conversion for you implicitly (if you're lucky!). Googling on the preferences of these two, it is clear that most people prefer the more explicit implicit conversion from JavaConverters
with the asScala
keyword.
Question 2: Is there a similar construction like JavaConverters
with RxScala? This would make the code above so much more cleaner, I would say:
import rx.lang.scala.JavaConverters._ // this class doesn't exist!
JavaFxObservable.fromObservableValue(textfield.textProperty())
.asScala
.map(s => /* do something */)
This question was the starting point of this pull request on the RxScala project.
The syntax proposed in the original question can be used by importing rx.lang.scala.JavaConverters
.
import rx.lang.scala.JavaConverters._
JavaFxObservable.fromObservableValue(textfield.textProperty())
.asScala
.map(s => /* do something */)
Likewise a Scala Observable
can be transformed into a Java Observable
using asJava
.
See also the examples of intended use.