Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java Void to Scala Unit

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?

like image 589
Luciano Avatar asked Dec 13 '22 22:12

Luciano


2 Answers

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.

like image 148
jqno Avatar answered Dec 21 '22 12:12

jqno


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.

like image 39
Luka Jacobowitz Avatar answered Dec 21 '22 10:12

Luka Jacobowitz