Ellen Spertus
10/28/2019, 6:45 PMVoid and has the following behavior:
override fun getResult(): Void {
if (!success) throw RuntimeException()
}
This doesn't compile, because a function with a block body requires a return statement.Ellen Spertus
10/28/2019, 6:47 PMJames
10/28/2019, 6:48 PMoverride fun getResult(): Unit {
if (!success) throw RuntimeException()
}James
10/28/2019, 6:48 PMkarelpeeters
10/28/2019, 6:49 PMJames
10/28/2019, 6:49 PMEllen Spertus
10/28/2019, 6:49 PMTask<Void>, which requires implementing getResult(): Void.Ellen Spertus
10/28/2019, 6:50 PMoverride fun getResult(): Void {
throw RuntimeException()
}Ellen Spertus
10/28/2019, 6:52 PMCasey Brooks
10/28/2019, 7:06 PMVoid has a private constructor, so it is impossible to actually get an instance of Void. Any method contract that requires you to return Void is implicitly requesting you return null instead. I think having your Kotlin method have a return type of Void? and returning null on the success branch is the way to go.Ellen Spertus
10/28/2019, 7:26 PMStephan Schroeder
10/29/2019, 10:39 AMoverride fun getResult(): Unit {
if (!success) throw RuntimeException()
} should work and is more idiomatic than Void?.
This playground code overrides Java’s Object’s finalize method which returns void in Java by using Unit and it works fine:
class KotlinObject() : java.lang.Object() {
override fun finalize(): Unit {}
}
https://pl.kotl.in/n_umKF6c8karelpeeters
10/29/2019, 11:42 AMTask<Void>.Stephan Schroeder
10/29/2019, 3:17 PMTask<Unit> but it does Task<Void?>, because technically Void? is as far from Void as is Unit. (What about ’Nothing?which is the same set as 'Void???)
I guess that the instance of Task<Void?> is passed back to Java code? Because otherwise using Task<Unit> is probably the answer. Something similar happens when I want to use the ExecutorService, which only handles `Callable`s and not `Runable`s. In that case Callable<Unit> is the way to go.Casey Brooks
10/29/2019, 3:21 PMTask<Unit> must return something, namely Unit.INSTANCE. Task<Void> does not make sense, since you cannot get a non-null instance of Void to return, and thus Task<Void?> must return nullCasey Brooks
10/29/2019, 3:22 PMUnit is analogous to void in the sense that it is the default return type, but it is not the same thing as void. void has no instance, unit has an instance and is non-null, and has a different meaning from void in Kotlin’s null-safe world