Jintin
10/24/2024, 11:15 PMStephan Schröder
10/25/2024, 8:12 AMUnit
is better than void
, e.g. because in Java you need two interfaces Runnable and Callable while in Kotlin Runnaable is made redundant by Callable<Unit> (in Java Callable<void> is not a thing). Of course this is a specialisation about how how every functional interface that returns something can also be used in a way that returns nothing inKlitos Kyriacou
10/25/2024, 8:52 AMCallable<Void>
. Admittedly, Void
is slightly different from void
.Stephan Schröder
10/25/2024, 9:25 AMVoid
, I just never used it -or seen it used- in my close to quarter century of using Java.
How do you construct an instance of it? But as you said, it's not void
, so Kotlin's type-sytem is indeed smoother in this respect.Klitos Kyriacou
10/25/2024, 9:32 AMHow do you construct an instance of it?You don't. The Java API documentation says "The
Void
class is an uninstantiable placeholder class to hold a reference to the Class object representing the Java keyword void."
But as you said, it's notKotlin's, so Kotlin's type-sytem is indeed smoother in this respect.void
Unit
is not void
either. Unit
is an object. From Java's point of view, Unit
is a class which has only one instance, Unit.INSTANCE
. This is analogous to Void
, which is a class that has no instances, so any Java method that returns a Void
type can only return null
, just as any Kotlin function that returns a Unit
type can only return the instance Unit
.Klitos Kyriacou
10/25/2024, 9:35 AMVoid
type is used in a few Java API methods; for example, CompletableFuture.allOf
returns a CompletableFuture<Void>
.Stephan Schröder
10/30/2024, 10:35 AMUnit
isn't void
, (though it "takes its place", there's probably a more correct formal way of stating this). I'm saying Unit
allows a more ellegant typesystem than one that uses void
.