I have a java library method requiring a class of Void
as a parameter. for example, in com.mongodb.async.client.MongoCollection
:
void insertOne(TDocument document, SingleResultCallback<Void> callback);
I'm accessing this method from scala. Scala uses the type Unit
as equivalent of Void
(correct me if I'm wrong please)
How can I pass a SingleResultCallback[Unit]
(instead of SingleResultCallback[Void]
) to this method? The compiler is not allowing this. Shouldn't it be picking this up?
Scala's Unit
is like Java's void
primitive, but it's not exactly the same thing.
Scala's Unit
type and Java's Void
type are completely unrelated. Java's Void
class exists so you can use it as a type parameter analogous to primitive void
, just like Integer
exists as an analogue to primitive int
. In Scala, Unit
fulfills the role of both Void
and void
.
An implicit conversion between Unit
and Void
cannot exist, because implicit conversions work on instances, not on types. Also, Java's Void
type cannot have an instance. (Scala's Unit
does have an instance: ()
.)
Long story short, Scala's Unit
and Java's Void
are different beasts. Since your Java library requires the Void
type parameter, you should just give it that.
Java's Void
is from my experience usually used with null
as its only value, where as Unit
also only has one value: ()
.
SingleResultCallback is just a SAM type of (T, Throwable) => Unit
. This means we can convert these from and to Unit
if we want:
def toUnit(cb: SingleResultCallback[Void]): SingleResultCallback[Unit] =
(u, throwable) => cb(null, throwable)
def fromUnit(cb: SingleResultCallback[Unit]): SingleResultCallback[Void] =
(v, throwable) => cb((), throwable)
This is assuming you use Scala 2.12.*. Otherwise you will need to construct an Instance of SingleResultCallback
using new
.
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