3

I accidentally hit enter after a value assignment and to my surprise it compiled perfectly fine!

What's the point of having this syntax? I tried to search for it online but only found articles about the Nothing-type, but nowhere close to this surprising syntax.

Syntax from IntelliJ Idea

2
  • 1
    Could you give an example of what your code looks like? Commented Jan 28, 2019 at 13:20
  • @AlexeySoshin I don't think it's relevant :) You can get this behaviour in any function when coding in IntelliJ IDEA (and probably also other IDE's) Commented Jan 28, 2019 at 13:44

1 Answer 1

4

Technically, return 123 is an expression which returns Nothing. Just like throw RuntimeException(). You can save the result of this expression in your variable but I cannot imagine how you can use it :)

Sign up to request clarification or add additional context in comments.

6 Comments

Oh is it possible that return 123 returns Nothing? shouldn't it return an Int?
I know that it's pretty hard to understand. A function with the line return 123 returns 123 but the line return 123 by itself has type Nothing
Welcome! Why not? It's a correct variable declaration. Just a bit useless :)
Because it's useless I guess xD I'm using Kotlin for 3 years now and I always was stunned by the choice of features they allowed into their language. It seemed to be in perfect balance. This stroke me as odd... Still a really good language by the way!
@PeterWillemsen it follows from the rule val name = expression. throw Exception() is a valid expression, so it has to have a type: Nothing. It is a valid expression, so it has to be assignable to a variable. Everything being an expression is really powerful, so it's a good thing.
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.