Skip to main content
Kotlin Language Fundamentals

Kotlin 101: A Beginner's Guide to Variables, Functions, and Control Flow

Welcome to Kotlin 101! This guide is your first step into the world of Kotlin, a modern, concise, and powerful programming language. We'll break down the three fundamental building blocks of any Kotli

图片

Welcome to Kotlin!

Kotlin has rapidly become a favorite among developers, especially for Android app development, but its uses extend far beyond. Designed to be fully interoperable with Java, Kotlin offers a more concise, safe, and expressive syntax. If you're new to programming or coming from another language, this guide will introduce you to the absolute essentials: variables, functions, and control flow. Mastering these three concepts is the key to unlocking your ability to build programs.

1. Storing Data with Variables

Variables are like labeled containers that hold your data. In Kotlin, you declare a variable using either val or var.

val vs. var

  • val (value): Declares an immutable reference. Once assigned, it cannot be reassigned. Use val by default.
  • var (variable): Declares a mutable reference. The value can be changed later.

Example:

val name = "Alice" // Immutable, cannot change
var score = 100 // Mutable, can change
score = 120 // This is allowed
// name = "Bob" // This would cause a COMPILER ERROR!

Basic Data Types

Kotlin is a statically-typed language, but it can often infer the type. Common basic types include:

  • Numbers: Int, Double, Long
  • Text: String
  • Logic: Boolean (true/false)

Example with explicit types:

val message: String = "Hello, World!"
val temperature: Double = 25.5
val isReady: Boolean = true

2. Defining Actions with Functions

Functions are reusable blocks of code that perform a specific task. They are declared using the fun keyword.

Basic Function Structure

fun functionName(parameter: ParameterType): ReturnType {
    // Code to execute
    return result
}

Example: A function that adds two numbers.

fun add(a: Int, b: Int): Int {
    val sum = a + b
    return sum
}
// Calling the function
val result = add(5, 3) // result is 8

Functions with Default and Single-Expression Bodies

Kotlin allows for concise function definitions.

Single-Expression: For simple functions, you can omit the braces and use the = symbol.

fun multiply(x: Int, y: Int): Int = x * y

Default Arguments: You can provide default values for parameters.

fun greet(user: String, greeting: String = "Hello") {
    println("$greeting, $user!")
}
greet("Bob") // Prints: Hello, Bob!
greet("Alice", "Good morning") // Prints: Good morning, Alice!

3. Controlling Your Code's Flow

Control flow statements determine the order in which your code executes. They allow you to make decisions and repeat actions.

Conditional Statements: if and when

if-else: Works much like in other languages, but in Kotlin, if can also be used as an expression that returns a value.

val max = if (a > b) {
    println("a is larger")
    a // This value is assigned to 'max'
} else {
    b
}

when: A powerful replacement for the switch statement found in other languages. It is very flexible.

val grade = 'B'
val feedback = when (grade) {
    'A' -> "Excellent!"
    'B', 'C' -> "Well done"
    else -> "Keep practicing!"
}
println(feedback) // Prints: Well done

Loops: for and while

Loops are used to repeat a block of code.

for loop: Iterates over anything that provides an iterator, like a range or a collection.

// Iterating over a range
for (i in 1..5) {
    println(i) // Prints 1, 2, 3, 4, 5
}
// Iterating over a list
val fruits = listOf("Apple", "Banana", "Orange")
for (fruit in fruits) {
    println(fruit)
}

while and do-while: Execute a block of code as long as a condition is true.

var counter = 3
while (counter > 0) {
    println("Countdown: $counter")
    counter--
}
// do-while executes the body at least once
var input: String
do {
    print("Enter 'yes': ")
    input = readLine() ?: ""
} while (input != "yes")

Putting It All Together

Let's write a small program that uses variables, a function, and control flow.

fun main() {
    val numbers = listOf(12, 5, 27, 8, 19)
    val threshold = 10

    println("Numbers greater than $threshold:")
    for (num in numbers) {
        if (isGreaterThan(num, threshold)) {
            println(num)
        }
    }
}

fun isGreaterThan(value: Int, limit: Int): Boolean = value > limit

Conclusion

Congratulations! You've taken your first steps into Kotlin programming. You now understand how to store data in val and var, organize logic into reusable functions with fun, and direct your program's execution with control flow statements like if, when, and for. These are the core pillars upon which all Kotlin applications are built. The next steps involve exploring more advanced topics like collections, classes, and Kotlin's fantastic null safety features. Keep practicing, and happy coding!

Share this article:

Comments (0)

No comments yet. Be the first to comment!