It seems a bit odd that I'm required to explicitly...
# announcements
l
It seems a bit odd that I'm required to explicitly state the return type of
Nothing
in this case...
Copy code
fun justThrowIt(): Nothing = throw IOException()
...while here, I'm not:
Copy code
fun justLoop() { while (true) {} }
d
The second function "returns" Unit.
☝️ 1
l
I can explicitly state the return type as
Nothing
and it does still compile.
a
fun justThrowIt() { throw IOException() }
works too
l
No, it doesn't.
"'Nothing' return type needs to be specified explicitly."
d
If you omit the return type, you've explicitly made it Unit.
a
my version is different from your version
d
If the method is an expression, then the return type is inferred.
IIRC,
throw ...
is not an expression.
l
@Andreas Sinz Oh gosh, you're right, it is different.
throw
is indeed an expression.
d
Oh is it?
l
Yeah:
Copy code
val result = try {
    println("Doing some I/O...")
    true
} catch (e: IOException) {
    println("Oops!")
    false
} finally {
    println("""In the "finally" block...""")
}
d
That's try and catch, not throw.
l
Ahaha sorry.
d
Can you do,
val something = throw IOException()
?
👌 4
l
Anyway, yeah:
Copy code
val x = throw IOException()
Totally compiles.
d
Oh, had no idea. Weird.
l
And the type of
x
appears to be
Nothing
, at least it still compiles if I explicitly state it as such.
a
throw
always "returns"
Nothing
l
OK, cool.
a
and btw,
while
is a statement, so a while-loop doesn't return anything
fun justLoop() = while(...) { }
doesn't compile
l
Yeah that's true.
So, as far as I can tell, in the case of
Copy code
fun justLoop() { while (true) {} }
The return type is
Unit
. It does still compile if I explicitly state return type of
Nothing
. I'd guess that the compiler would enforce return type of
Nothing
if it were smart enough to know that the function never returns, but I guess it isn't.
d
If
throw
"returns"
Nothing
, then why doesn't
fun justThrowIt() = throw IOException()
work? Strange.
l
Well it does "work", in a sense, you're only required to state
Nothing
as the return type, as in
Copy code
fun justThrowIt(): Nothing = throw IOException()
That will compile.
a
@Dominaezzz it does work fine, you get the error Nothing return type needs to be specified explicitly so you don't accidentally return
Nothing
from a function
d
Oh okay. That makes sense.