From the course: Kotlin Essential Training: Functions, Collections, and I/O

Unlock the full course today

Join today to access over 24,900 courses taught by industry experts.

Statements vs. expressions

Statements vs. expressions

- [Instructor] If and when can both be used both as statements and expressions. So how do we know the difference in when should we use one form or the other? To understand the difference and why it's important, we're going to examine the use of if and when as expressions to demonstrate how we can write safer, more concise code. A statement doesn't return any value. An expression, on the other hand, will either have its value returned from a function or assigned to a variable. We can use an if-expression to conditionally assign a variable's name. So let's create a variable called message, and then we can use our equals, and now when we go to assign the value of this variable, rather than just assigning a static constant here, we could use an if-expression to change the value assigned, depending on some variable value. So let's create a variable, var someVariable equals. Let's just say zero for now. So now when we go to…

Contents