Search code examples
javascalavoidscalacscala-compiler

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?


Solution

  • 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.