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 - Kotlin Tutorial
From the course: Kotlin Essential Training: Functions, Collections, and I/O
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
-
-
-
-
-
-
(Locked)
if and when statements12m 55s
-
(Locked)
Statements vs. expressions7m 19s
-
(Locked)
try/catch as control flow6m 25s
-
(Locked)
Smart casting11m 44s
-
(Locked)
while loops5m 17s
-
(Locked)
for loops3m 49s
-
(Locked)
Challenge: Replace an if/else expression with a when expression1m 12s
-
(Locked)
Solution: Replace an if/else expression with a when expression5m 15s
-
(Locked)
-
-
-
-
-