No it wouldn’t. Maybe my example above wasn’t perfect. You can’t just evaluate a type at runtime. This is all done at compile time. In your example
s will have the same type as
Every expression has only one type which will be determined at compile time. For some expressions this is constant, eg.
return expression is always of type
Nothing and a string literal
"foo" will always be of type
String. For other expressions this has to be determined by the compiler.
a + b for example depends on the types of
b. Same is true for
name ?: return.
name has one type lets use
return has the type
Nothing. I don’t think this is stated anywhere (since this is going into implementation details) but the compiler will have some sort of rule that state: “The type of an elvis operator will be the most specific supertype of both arguments”. This means the compiler will now look for the most specific supertype of
Nothing is a subtype of every other type this will be
String. Therefor the expression
name ?: return will be of type
Well there are pretty much 2 options. Either
return is a statement or an expression.
If it’s a statement it doesn’t have a type, but it also couldn’t be used as part of another expression.
val n = name ?: return would be invalid since
return is a statement and can’t be used inside of a larger expression.
I guess you could add special cases for
return, etc but that would just make the compiler far more complicated and would probably just introduce bugs.
The other option is that
return is an expression. In that case it can be used in any other larger expression but it also needs a type.
return will never actually “return” a value to the expression it is used in (it will return from the function instead) and you want to use it in any expression regardless of what type the expression requires (you might want to use
return for both
Those 2 criteria are coverd by a special kind of type called a Bottom Type. In kotlin this bottom type is called
The most common use cases for
return as an expression is the one above (
val foo = bar ?: return)
Of cause all of this also applies to
continue, as well as
throw which is a 4th expression that is of type
For more uses of the
Nothing type in kotlin you should read
Otherwise I wouldn’t worry much about it. As I said earlier most of this is just some nice way of defining those expressions to make the implementation easier (in the kotlin compiler).