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 use Kotlin data types like String, Int, and Boolean?

In Kotlin, data types like String, Int, and Boolean are fundamental types that are used to work with text, numbers, and logical values respectively. Kotlin provides these types as part of its standard library, and they are straightforward to use. Below is an explanation of how to work with them:

1. String

A String in Kotlin represents a sequence of characters. You can create and manipulate strings easily.

Example:

fun main() {
    val name: String = "Kotlin"
    val greeting = "Hello, $name!" // String interpolation
    val length = name.length       // Access string property

    println(greeting)  // Output: Hello, Kotlin!
    println("Length of name: $length")  // Output: Length of name: 6

    // Multi-line string
    val multiLineString = """
        This is a
        multi-line string.
    """.trimIndent()

    println(multiLineString)
}

Key Features of Strings:

  • String interpolation ($) to include variables or expressions within a string.
  • Supports multi-line strings using triple quotes (""").
  • String manipulation methods, e.g., .length, .substring(), .toUpperCase(), etc.

2. Int

An Int is a basic data type representing a 32-bit integer in Kotlin. It is used for whole numbers.

Example:

fun main() {
    val number: Int = 42
    val doubled = number * 2
    val isEven = number % 2 == 0

    println("Number: $number")  // Output: Number: 42
    println("Doubled: $doubled")  // Output: Doubled: 84
    println("Is even? $isEven")  // Output: Is even? true
}

Key Points:

  • Int is one of the numeric data types, which also include Long, Short, Byte, Double, and Float.
  • Kotlin handles mathematical operations with Int and other numeric types directly.
  • Reading and writing numbers are simple, and type conversion can be performed using .toInt(), .toDouble(), etc.

3. Boolean

A Boolean in Kotlin represents a value that is either true or false.

Example:

fun main() {
    val isKotlinFun: Boolean = true
    val isJavaFun = false

    println("Is Kotlin fun? $isKotlinFun")  // Output: Is Kotlin fun? true
    println("Is Java fun? $isJavaFun")      // Output: Is Java fun? false

    // Logical operations
    val bothFun = isKotlinFun && isJavaFun  // AND operation
    val eitherFun = isKotlinFun || isJavaFun // OR operation

    println("Both fun? $bothFun")  // Output: Both fun? false
    println("Either fun? $eitherFun") // Output: Either fun? true
}

Key Points:

  • Booleans are used for logical operations and for controlling conditions in if statements, loops, etc.
  • Supports logical operators: && (AND), || (OR), ! (NOT).

Type Inference

In Kotlin, thanks to type inference, you don’t always need to explicitly specify the type of a variable. The compiler can infer the type based on the assigned value.

Example:

fun main() {
    val name = "Kotlin"  // Automatically inferred as String
    val age = 25         // Automatically inferred as Int
    val isActive = true  // Automatically inferred as Boolean

    println(name)
    println(age)
    println(isActive)
}

Additional Tips

  • Type Conversion: When converting between data types (e.g., String to Int), use methods like toInt(), toDouble(), etc.
    val number = "123".toInt()  // Converts String to Int
    val decimal = 3.14.toString()  // Converts Double to String
    
  • Null Safety: These types are non-null by default. If you want a variable to hold a null value, use the nullable types (e.g., String?, Int?, Boolean?).
    val nullableString: String? = null
    

With those basics, you are ready to work with String, Int, and Boolean in Kotlin!

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.