Kotlin - Language Fundamentals & Syntax

Kotlin Language Fundamentals

Master the essential building blocks of Kotlin: syntax rules, identifiers, keywords, comments, and the basic structure that makes Kotlin programs work.

Basic Syntax Rules

Case Sensitivity

Kotlin is case-sensitive, meaning main, Main, and MAIN are different:

fun main() { }     // ✅ Correct entry point
fun Main() { }     // ❌ Different function
fun MAIN() { }     // ❌ Different function

Semicolons are Optional

Unlike Java, semicolons are optional in Kotlin:

Valid Kotlin

fun main() {
    println("Hello")
    val x = 5
    println(x)
}

Also Valid (but not idiomatic)

fun main() {
    println("Hello");
    val x = 5;
    println(x);
}

Whitespace and Indentation

Kotlin ignores extra whitespace, but consistent indentation improves readability:

fun main() {
    val name = "Kotlin"    // 4 spaces indentation (recommended)
    if (name.isNotEmpty()) {
        println(name)      // 8 spaces for nested blocks
    }
}
Style Note: Use 4 spaces for indentation (not tabs). Most IDEs can be configured to do this automatically.

Identifiers

Naming Rules

Identifiers are names for variables, functions, classes, etc. They must:

  • Start with a letter (a-z, A-Z) or underscore (_)
  • Contain only letters, digits (0-9), and underscores
  • Not be a Kotlin keyword
  • Be case-sensitive

✅ Valid Identifiers

name
firstName
age2
_count
userName
MAX_SIZE
isValid
calculate_tax

❌ Invalid Identifiers

2name        // starts with digit
first-name   // contains hyphen
class        // keyword
my name      // contains space
@username    // contains @

Naming Conventions

  • Functions and Variables: camelCase (firstName, calculateTax)
  • Classes: PascalCase (UserAccount, BankService)
  • Constants: UPPER_SNAKE_CASE (MAX_SIZE, DEFAULT_TIMEOUT)
  • Packages: lowercase (com.example.myapp)

Keywords

Keywords are reserved words that have special meaning in Kotlin:

Basic Keywords

  • fun - function
  • val - immutable variable
  • var - mutable variable
  • class - class declaration
  • if, else - conditionals
  • when - switch expression

Loop Keywords

  • for - for loop
  • while - while loop
  • do - do-while loop
  • break - exit loop
  • continue - skip iteration

OOP Keywords

  • open - inheritable
  • abstract - abstract class
  • interface - interface
  • object - singleton object
  • companion - companion object

Comments

Comments explain code and are ignored by the compiler:

Single-Line Comments

fun main() {
    // This is a single-line comment
    println("Hello") // Comment at end of line
}

Multi-Line Comments

/*
 * This is a multi-line comment
 * It can span multiple lines
 * Useful for longer explanations
 */
fun main() {
    /* Short multi-line comment */
    println("Hello")
}

Documentation Comments (KDoc)

/**
 * Calculates the area of a rectangle
 * @param width the width of the rectangle
 * @param height the height of the rectangle
 * @return the area as a Double
 */
fun calculateArea(width: Double, height: Double): Double {
    return width * height
}
Teacher Note: KDoc comments are similar to JavaDoc and can be used to generate documentation. Encourage students to document their functions from early on.

Expressions vs Statements

Expressions

Expressions produce a value and can be used wherever a value is expected:

fun main() {
    val a = 5 + 3           // 5 + 3 is an expression
    val b = if (a > 5) 10 else 0  // if is an expression in Kotlin
    val c = when (a) {      // when is also an expression
        8 -> "eight"
        else -> "other"
    }
}

Statements

Statements perform an action but don't return a value:

fun main() {
    println("Hello")        // Statement: performs action
    val x = 5              // Statement: declares variable
}
Key Difference: In Kotlin, many constructs that are statements in Java (like if and when) are expressions, making code more concise.

Code Blocks

Code blocks are groups of statements enclosed in curly braces:

fun main() {                    // Function block
    val name = "Kotlin"
    
    if (name.isNotEmpty()) {    // If block
        println("Name: $name")
        println("Length: ${name.length}")
    }
    
    run {                       // Anonymous block
        val temp = "temporary"
        println(temp)
    }
    // temp is not accessible here
}

String Literals

Regular Strings

val greeting = "Hello, World!"
val name = "Kotlin"
val empty = ""

String Templates

val name = "Alice"
val age = 30
val message = "Hello, $name! You are $age years old."
val calculation = "5 + 3 = ${5 + 3}"

Raw Strings

val multiLine = """
    Line 1
    Line 2
    Line 3
    """.trimIndent()

val path = """C:\Users\name\Documents"""  // No need to escape backslashes

Basic Operators

Arithmetic Operators

val a = 10
val b = 3

println(a + b)  // Addition: 13
println(a - b)  // Subtraction: 7
println(a * b)  // Multiplication: 30
println(a / b)  // Division: 3
println(a % b)  // Modulus: 1

Assignment Operators

var x = 10
x += 5    // x = x + 5, result: 15
x -= 3    // x = x - 3, result: 12  
x *= 2    // x = x * 2, result: 24
x /= 4    // x = x / 4, result: 6

Comparison Operators

val a = 10
val b = 5

println(a > b)   // Greater than: true
println(a < b)   // Less than: false
println(a >= b)  // Greater than or equal: true
println(a <= b)  // Less than or equal: false
println(a == b)  // Equal: false
println(a != b)  // Not equal: true

Program Structure

Basic Structure

// Optional package declaration
package com.example.myapp

// Import statements
import kotlin.math.*

// Top-level declarations
val CONSTANT = "Global constant"

// Main function (entry point)
fun main() {
    println("Program starts here")
}

// Other functions
fun helper() {
    println("Helper function")
}

File Organization

  • One file can contain multiple classes and functions
  • File name doesn't need to match class name (unlike Java)
  • Top-level functions are allowed
  • Package structure should match directory structure
Architecture Note: Kotlin's flexibility in file organization allows for better code organization. You can group related functions and classes in the same file, reducing the number of files in large projects.

Common Syntax Patterns

Variable Declaration Pattern

val readOnly = "immutable"      // Type inferred
var mutable: String = "can change"  // Explicit type
lateinit var delayed: String    // Late initialization

Function Declaration Pattern

fun functionName(param1: Type, param2: Type): ReturnType {
    // function body
    return result
}

// Single expression function
fun add(a: Int, b: Int): Int = a + b

// No return type needed for Unit
fun printHello() {
    println("Hello")
}

Error Prevention Tips

Common Beginner Mistakes

  • Using Java syntax: System.out.println instead of println
  • Forgetting fun keyword in function declarations
  • Using = instead of == for comparison
  • Not understanding val vs var differences
  • Inconsistent naming conventions

Practice Exercises

  1. Write a program with proper comments explaining each line
  2. Create variables with different naming styles and identify which follow conventions
  3. Experiment with string templates using different expressions
  4. Write a function that demonstrates the difference between expressions and statements

Quick Quiz

  1. Are semicolons required at the end of statements in Kotlin?
  2. What naming convention should you use for function names?
  3. Can you use a Kotlin keyword as a variable name?
  4. What symbol starts a single-line comment in Kotlin?
Show answers
  1. No, semicolons are optional in Kotlin
  2. camelCase (e.g., calculateTax, firstName)
  3. No, keywords are reserved and cannot be used as identifiers
  4. // (double slash)