Discussion
In a valid throw statement, the input slot on the right of the throw keyword must be filled by a Throwable exception. A return statement isn’t a value at all, let alone a Throwable—so why is it a valid way to fill this slot?
Any time Kotlin’s type checker is expecting a value of a specific type, it’ll also accept an instruction that prevents the program from reaching the place where the value is required. In this puzzle, we’re exploiting that twice in quick succession—first when we use throw in place of a real value for the boomerang variable, and again when we use return in place of the exception to throw.
Value Not Found
You probably already know that any time you don’t want to return a value from a function, you can throw an exception ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access