4

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?

Luciano
  • 2,388
  • 1
  • 22
  • 33

3 Answers3

9

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.

jqno
  • 15,133
  • 7
  • 57
  • 84
4

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.

Luka Jacobowitz
  • 22,795
  • 5
  • 39
  • 57
0

Try javatoscala

It returned:

def insertOne(document: TDocument,
                callback: SingleResultCallback[Void]): Unit
Ori Marko
  • 56,308
  • 23
  • 131
  • 233
  • Sorry but this doesn't answer my question. I want to pass callback = `SingleResultCallback[Unit]`, not `SingleResultCallback[Void]` to this method. How do I do that? There is no implicit conversion from `Void` to `Unit`. – Luciano Jul 06 '17 at 11:13