How do I use the when expression as a switch alternative in Kotlin?

In Kotlin, the when expression can be used as an alternative to the traditional switch statement found in languages like Java. The when expression is versatile, concise, and supports a wide range of matching conditions. Here’s how you can use it:

Examples of Using the when Expression

  1. Using when as a simple switch:
    fun getResponse(code: Int): String {
       return when (code) {
           200 -> "OK"
           404 -> "Not Found"
           500 -> "Internal Server Error"
           else -> "Unknown Code"
       }
    }
    
  2. Multiple matches for a single branch:
    You can check multiple values by separating them with a comma.

    fun isWeekend(day: String): Boolean {
       return when (day) {
           "Saturday", "Sunday" -> true
           else -> false
       }
    }
    
  3. Range checking:
    You can check if a value falls within a certain range.

    fun categorizeAge(age: Int): String {
       return when (age) {
           in 0..12 -> "Child"
           in 13..19 -> "Teenager"
           in 20..59 -> "Adult"
           else -> "Senior"
       }
    }
    
  4. Type checking:
    The is keyword can be used to check the type of a variable.

    fun describe(obj: Any): String {
       return when (obj) {
           is String -> "It's a string of length ${obj.length}"
           is Int -> "It's an integer"
           else -> "Unknown type"
       }
    }
    
  5. Checking conditions (arbitrary boolean expressions):
    You can use boolean expressions inside the when expression.

    fun checkNumber(num: Int): String {
       return when {
           num < 0 -> "Negative Number"
           num == 0 -> "Zero"
           num > 0 -> "Positive Number"
           else -> "Unknown"
       }
    }
    
  6. when without an argument:
    You can omit the argument from when if you just want to match conditions.

    fun getResult(value: Int): String {
       return when {
           value % 2 == 0 -> "Even"
           value % 2 != 0 -> "Odd"
           else -> "Unknown"
       }
    }
    

when as an Expression vs Statement

In Kotlin, when is an expression, which means it can return a value:

val message = when (val age = 25) {
    in 0..12 -> "You're a child"
    in 13..19 -> "You're a teenager"
    else -> "You're an adult"
}
println(message)

But you can also use it as a statement if you don’t need the result:

fun printMessage(code: Int) {
    when (code) {
        200 -> println("Request was successful")
        404 -> println("Resource not found")
        else -> println("Unexpected response code")
    }
}

Summary

The when expression in Kotlin allows for cleaner and more expressive code compared to a traditional switch statement. It supports:

  • Multiple case matching.
  • Type checking.
  • Arbitrary conditions.
  • Use as a statement or an expression.

This flexibility makes it a powerful tool for decision-making in Kotlin!

How do I define and call functions in Kotlin?

In Kotlin, defining and calling functions is straightforward and follows a clear syntax. Here’s how you can define and use functions:

Defining a Function

The fun keyword is used to define a function in Kotlin.

Basic Syntax:

fun functionName(parameters: ParameterType): ReturnType {
    // Function body
    return someValue // Optional if the return type is Unit (void equivalent in Kotlin)
}

Example – A Function without Parameters and Return Type (Unit):

fun sayHello() {
    println("Hello, World!")
}

Function with Parameters:

fun greet(name: String) {
    println("Hello, $name!")
}

Function with Parameters and a Return Type:

fun add(a: Int, b: Int): Int {
    return a + b
}

Calling a Function

You simply call the function by its name and pass the required arguments (if any).

Examples:

  1. Calling a Function without Arguments:
    sayHello() // Output: Hello, World!
    
  2. Calling a Function with Arguments:
    greet("Alice") // Output: Hello, Alice!
    
  3. Calling a Function with Return Value:
    val sum = add(5, 3)
    println("Sum: $sum") // Output: Sum: 8
    

Default Parameters

Functions in Kotlin can have default parameter values. If a parameter is not provided during function call, the default value is used.

fun greet(name: String = "Guest") {
    println("Hello, $name!")
}

// Usage
greet()          // Output: Hello, Guest!
greet("Alice")   // Output: Hello, Alice!

Single-Expression Functions

If a function contains only a single expression, you can use the = symbol without curly braces:

fun square(x: Int): Int = x * x

// Usage
println(square(4)) // Output: 16

Named Arguments

When calling a function, you can specify arguments by their parameter names for better readability.

fun displayInfo(name: String, age: Int) {
    println("Name: $name, Age: $age")
}

// Usage
displayInfo(age = 25, name = "John") // Output: Name: John, Age: 25

Vararg Parameters (Variable Number of Arguments)

You can pass a variable number of arguments to a function using the vararg keyword.

fun printAll(vararg items: String) {
    for (item in items) {
        println(item)
    }
}

// Usage
printAll("Apple", "Banana", "Cherry")
// Output:
// Apple
// Banana
// Cherry

Higher-Order Functions (Functions that Take or Return Functions)

Function Taking Another Function as a Parameter:

fun applyOperation(x: Int, y: Int, operation: (Int, Int) -> Int): Int {
    return operation(x, y)
}

// Usage
val result = applyOperation(4, 5) { a, b -> a + b } // Lambda as a parameter
println(result) // Output: 9

Function Returning Another Function:

fun getMultiplier(factor: Int): (Int) -> Int {
    return { number -> number * factor }
}

// Usage
val multiplier = getMultiplier(3)
println(multiplier(5)) // Output: 15

By using these techniques, you can write concise and powerful functions in Kotlin.

How do I use if expressions for decision-making in Kotlin?

In Kotlin, if expressions are used for decision-making. Unlike some other programming languages, Kotlin’s if is an expression, meaning it returns a value. This makes it more versatile because it can be directly assigned to a variable or used in a function return.

Here’s how it works:

1. Basic if expression

The simplest usage is just like a usual if statement:

val number = 10

if (number > 0) {
    println("$number is positive")
}

2. if-else expression

Kotlin’s if can be combined with else to define two branches of logic:

val number = -5

if (number > 0) {
    println("$number is positive")
} else {
    println("$number is non-positive")
}

3. Using if as an expression

The key feature of Kotlin’s if is that it returns a value. This means you can assign the result of an if to a variable:

val number = 15

val result = if (number % 2 == 0) {
    "Even"
} else {
    "Odd"
}

println("The number is $result")

Here, the value of result will be "Odd" because number is 15.

4. if with multiple branches

You can include more than two branches by chaining multiple else if conditions:

val number = 0

val result = if (number > 0) {
    "Positive"
} else if (number < 0) {
    "Negative"
} else {
    "Zero"
}

println("The number is $result")

5. Returning block results

When using an if expression with blocks (multiple lines), the last expression in each block is the value that gets returned:

val a = 10
val b = 20

val max = if (a > b) {
    println("a is greater")
    a  // This value is returned
} else {
    println("b is greater")
    b  // This value is returned
}

println("Maximum is $max")

6. if as a shorthand

For simple conditions, you can write the if expression in a single line:

val age = 18
val isAdult = if (age >= 18) "Adult" else "Minor"

println("You are $isAdult")

In this case, there’s no need for curly braces.

Notes:

  • if expressions must always cover all cases when used to assign a result. If you omit the else branch and none of the conditions are met, the code will result in a compilation error.
  • For decision-making scenarios with many options, consider using when expressions for more readability.

How do I declare variables in Kotlin using val and var?

In Kotlin, you can declare variables using two keywords: val and var. The choice between them depends on whether you want the variable to be immutable or mutable.

1. Declaring Immutable (Read-Only) Variables with val

  • Use val when the value of the variable will not change after it is initialized.
  • The variable becomes read-only (similar to final in Java).

Syntax:

val variableName: Type = value

Example:

val name: String = "John"
// name = "Jane" // This will cause a compilation error

Kotlin can also infer the type automatically if it can be deduced from the value:

val age = 30 // Kotlin infers that 'age' is of type Int

2. Declaring Mutable Variables with var

  • Use var when the value of the variable can change during the program’s lifecycle.
  • The variable becomes mutable.

Syntax:

var variableName: Type = value

Example:

var age: Int = 25
age = 26 // This is allowed because 'age' is mutable

Similarly, type inference can be used:

var firstName = "John" // Kotlin infers that it's a String
firstName = "Jane" // Allowed because 'firstName' is mutable

Key Differences Between val and var

Aspect val var
Mutability Immutable (read-only) Mutable (modifiable)
Reassignment Not allowed Allowed
Use Case When a value should not change When a value needs to change

Additional Examples

Example 1: Declaring Variables with Explicit Types

val city: String = "New York"
var temperature: Double = 25.5
temperature = 30.0 // This is valid

Example 2: Using Type Inference

val country = "USA" // 'country' is inferred to be a String
var isRaining = false // 'isRaining' is inferred to be a Boolean
isRaining = true // Valid because 'isRaining' is mutable

Important Notes

  • For complex objects (like lists and maps), val does not mean the contents of the object cannot change; it just means the variable reference cannot be reassigned.
val list = mutableListOf(1, 2, 3)
list.add(4) // Allowed, because the contents of the list are mutable
// list = mutableListOf(5, 6, 7) // Not allowed, because 'list' is immutable
  • Try to prefer val over var wherever possible to make your code safer and easier to reason about.

How do I write my first Kotlin program?

Writing your first Kotlin program is simple! Follow these steps to create, write, and run your first Kotlin program:

Step 1: Set Up Your Environment

To write Kotlin programs, you need a development environment. The recommended setup is IntelliJ IDEA, which is specifically designed for Kotlin development.

  1. Download and Install IntelliJ IDEA:
    • Visit JetBrains’ IntelliJ IDEA.
    • Download the Ultimate Edition (for Java/Kotlin development) or Community Edition (free version).
    • Install it.
  2. Install Kotlin Plugin:
    • Kotlin support is built into IntelliJ IDEA. If it’s not already installed, go to: File → Settings → Plugins (Windows/Linux) or IntelliJ IDEA → Preferences → Plugins (Mac).
    • Search for “Kotlin” in the marketplace, and install it.

Step 2: Create a New Kotlin Project

  1. Open IntelliJ IDEA and click on:
    • New Project.
  2. Select Kotlin under “Languages” or “New Project Wizard.”
    • Choose Kotlin/JVM as the project type.
  3. Configure your Project:
    • Specify the project name (e.g., “FirstKotlinApp”).
    • Choose or create a project location.
    • Make sure you add a JDK (Java Development Kit). If not installed, download a JDK from AdoptOpenJDK or Oracle JDK.
  4. Click Finish to create the project.

Step 3: Write Your First Kotlin Code

  1. In the src folder, create a new Kotlin file:
    • Right-click src → New → Kotlin File/Class.
    • Name it something like HelloWorld.
  2. Write your Kotlin code. Here’s your first program:

    fun main() {
       println("Hello, Kotlin!")
    }
    

Step 4: Run Your Program

  1. Run the program by clicking the green play icon next to the main function or at the top of the editor.
  2. Alternatively, run it by right-clicking the file and selecting:
    • Run 'HelloWorldKt'.
  3. You should see the output in the Run Tool Window at the bottom of the IDE:
    Hello, Kotlin!
    

Understanding the Code

  • fun: This keyword defines a function.
  • main: This is the entry point of the program, similar to main in Java.
  • println: A function that prints a line of text to the console.

Congratulations!

You’ve successfully written and executed your first Kotlin program!

Install IntelliJ IDEA Community Edition and Write Hello Kotlin Program

To write Kotlin program you will need an IDE (Integrated Development Environment). One of the IDE that you can use is the IntelliJ IDEA CE (Community Edition). It comes with Kotlin Java Runtime Library, so you don’t need to install it separately.

To run Kotlin program you will need to install the latest JDK (Java Development Kit) which can be downloaded freely from the Java Download Website. Download version for your operating system and run the installer.

To check if Java successfully installed you can type the following command in your terminal or command prompt:

java -version

If you see something this then Java Development Kit is installed in your system.

java version "17" 2021-09-14 LTS
Java(TM) SE Runtime Environment (build 17+35-LTS-2724)
Java HotSpot(TM) 64-Bit Server VM (build 17+35-LTS-2724, mixed mode, sharing)

After installing the JDK you can download the IntelliJ IDEA CE. Double-click the installer to install it. For more details on installation and set up you can check out this website.

Now let’s create our first simple Kotlin program in IntelliJ IDEA.

  • Open the IntelliJ IDEA CE and click the Create New Project from the Welcome Screen dialog.
Create New Kotlin Project

Create New Kotlin Project

  • On the New Project dialog choose Kotlin from the left sidebar and then choose Kotlin/JVM in the selection on the right sidebar. Press the Next button.
New Kotlin Project Setup

New Kotlin Project Setup

  • Enter the project name Hello Kotlin, the project location path and the JDK will be used in the project.
New Kotlin Project Configurations

New Kotlin Project Configurations

  • Click the Finish button to create the project. It will bring you to the following screen.
HelloKotlin Project in IntelliJ IDEA CE

HelloKotlin Project in IntelliJ IDEA CE

  • Right-click on the src directory and choose NewKotlin File/Class from the menu. Enter HelloKotlin in the File/Class name.
New Kotlin File/Class Dialog

New Kotlin File/Class Dialog

  • In the HelloKotlin.kt type in the following code snippet.
fun main(args: Array<String>) {
    if (args.isEmpty()) {
        println("Hello, World!")
        return
    } else {
        println("Hi, hello ${args[0]}!")
    }
}
  • To run it, right-click on the editor and choose the Run HelloKotlinKt from the menu.
  • If you want to run it with an argument, you can set it in the Run/Debug Configurations dialog.
  • To open the Run/Debug Configurations click the down-arrow button next to HelloKotlinKt in the navigation bar on the top-right and choose Edit Configurations…
  • Type in the arguments in the Program arguments textbox.
Run/Debug Configurations

Run/Debug Configurations

That’s all. Now you have your JDK, IntelliJ IDEA CE installed and created your first Kotlin program. If you have any questions, please post it in the comments section below. Thank you and have fun with Kotlin.

How do I write Hello World in Kotlin?

In Kotlin, the HelloWorld.kt program can be written as a simple function like the following snippet.

fun main(args: Array<String>) {
    println("Hello, World!")
}

From this little code snippet we can learn the following features of the Kotlin programming language:

  • Kotlin program saved in a file with .kt extension.
  • The fun keyword to declare a function to show you that programming can be fun again 😉
  • To declare variables we start with the variable name followed by its type separated by a colon.
  • We don’t have to end a statement with a semicolons.
  • To print we can use the println function, which is a wrapper to Java System.out.println.
  • The main function is the execution entry point of our HelloWorld program.
  • We can create functions at the top level file without creating a class.

To compile the HelloWorld.kt program we run the following command:

kotlinc HelloWorld.kt

The compiler creates a class file called HelloWorldKt.class. To run it type the following command, assumed that you’ve set up the $KOTLIN_LIB environment variable. In my case the variable is set to /usr/local/Cellar/kotlin/1.2.40/libexec/lib.

java -cp $KOTLIN_LIB/kotlin-stdlib.jar:. HelloWorldKt