Landry Norris
08/31/2022, 8:34 PMfun foo(x: Int) = myWrapper {
doSomething();
}
where the wrapper function has a signature like
fun <T> myWrapper(() -> T): T
This works well for most cases except where I want foo to return Unit and doSomething() has a return type. In this case, I have to change the sample to
fun foo(x: Int) = myWrapper {
doSomething();
Unit //return Unit
}
Is there a way to tell the compiler that if the function foo has a return type of Unit, it should ignore the value returned by doSomething(), and treat it like a normal statement, similar to if I didn’t have my wrapper?ephemient
08/31/2022, 8:54 PMfun foo(): Unit = myWrapper { doSomething() }
fun foo() = myWrapper<Unit> { doSomething() }
either one will workLandry Norris
08/31/2022, 9:01 PMType mismatch.
Required:
Unit
Found:
Int
Where ‘Int’ is the return type of doSomething.Landry Norris
08/31/2022, 9:02 PMephemient
08/31/2022, 9:07 PMephemient
08/31/2022, 9:08 PMfun foo() {
myWrapper { doSomething() }
}
is also possibleLandry Norris
08/31/2022, 9:11 PMType mismatch.
Required:
Unit
Found:
Unit?
Unit?
doesn’t have any real meaning, does it?ephemient
08/31/2022, 9:14 PMLandry Norris
08/31/2022, 9:17 PMLandry Norris
08/31/2022, 9:23 PM?: Unit
to the end of the wrapper definition. The main use I have for wrapper functions like this is converting Kotlin/Native exceptions to JVM exceptions using JNI. My JNI methods are all wrapped in a handleException(block: () -> T): T
that will call block
and catch some recognized exceptions, then instantiate the JVM equivalent and ask the JVM to throw it. I use the fun foo() = handleException ...
to make it clear to the developer that handling exceptions isn’t a fundamental part of the job of foo, but something it does for correctness. I’ve always liked Kotlin’s syntax for this, especially with things like withContext(Dispatcher).ephemient
08/31/2022, 9:28 PMNothing
is the bottom type, Unit
is the unit type, and ?
is | null
. so of course Nothing?
and Unit?
have meanings: the former is only inhabited by the value null
(and ⟂
), the latter is inhabited by Unit
and null
(and ⟂
)Youssef Shoaib [MOD]
08/31/2022, 10:35 PMNothing
is the bottom type (i.e. ⊥
) but I wouldn't necessarily say that ⊥
is an inhabitant of Nothing
. This is different from Haskell having bottoms as a value because Haskell is lazy and so ⊥
is really a () -> Nothing
ephemient
08/31/2022, 10:40 PM⟂
a "value" is questionable even in Haskellephemient
08/31/2022, 10:40 PMephemient
08/31/2022, 10:41 PM