In this section, we will cover the fundamental concepts of variables and data types in Kotlin. Understanding these basics is crucial as they form the foundation for more advanced topics.

Key Concepts

  1. Variables:

    • val (Immutable variable)
    • var (Mutable variable)
  2. Data Types:

    • Primitive Data Types: Int, Double, Float, Long, Short, Byte, Boolean, Char
    • Non-Primitive Data Types: String, Array, List, Set, Map
  3. Type Inference:

    • Kotlin can infer the type of a variable based on the assigned value.
  4. Nullable Types:

    • Handling null values with ? and the !! operator.

Variables

Immutable Variables (val)

In Kotlin, val is used to declare a read-only variable. Once a value is assigned to a val variable, it cannot be changed.

val name: String = "John"
val age: Int = 30

// name = "Doe" // This will cause a compilation error

Mutable Variables (var)

var is used to declare a mutable variable. The value of a var variable can be changed.

var city: String = "New York"
city = "Los Angeles" // This is allowed

Data Types

Primitive Data Types

Kotlin provides several primitive data types:

Data Type Description Example
Int 32-bit integer val num: Int = 10
Double 64-bit floating point val pi: Double = 3.14
Float 32-bit floating point val e: Float = 2.71f
Long 64-bit integer val bigNum: Long = 100000L
Short 16-bit integer val smallNum: Short = 1
Byte 8-bit integer val byteNum: Byte = 127
Boolean True or false val isKotlinFun: Boolean = true
Char Single character val letter: Char = 'A'

Non-Primitive Data Types

Kotlin also provides non-primitive data types:

  • String: A sequence of characters.

    val greeting: String = "Hello, Kotlin!"
    
  • Array: A collection of elements of the same type.

    val numbers: Array<Int> = arrayOf(1, 2, 3, 4, 5)
    
  • List: An ordered collection of elements.

    val fruits: List<String> = listOf("Apple", "Banana", "Cherry")
    
  • Set: A collection of unique elements.

    val uniqueNumbers: Set<Int> = setOf(1, 2, 3, 4, 5)
    
  • Map: A collection of key-value pairs.

    val countryCodes: Map<String, String> = mapOf("US" to "United States", "IN" to "India")
    

Type Inference

Kotlin can infer the type of a variable based on the assigned value, so you don't always need to explicitly specify the type.

val inferredInt = 10 // Kotlin infers this as Int
val inferredString = "Hello" // Kotlin infers this as String

Nullable Types

In Kotlin, you can explicitly specify that a variable can hold a null value by using the ? operator.

var nullableName: String? = "John"
nullableName = null // This is allowed

To safely access a nullable variable, you can use the safe call operator ?. or the Elvis operator ?:.

val length: Int? = nullableName?.length // Safe call
val lengthOrZero: Int = nullableName?.length ?: 0 // Elvis operator

If you are sure that the variable is not null, you can use the non-null assertion operator !!.

val length: Int = nullableName!!.length // Throws NullPointerException if nullableName is null

Practical Exercises

Exercise 1: Declare Variables

  1. Declare an immutable variable firstName of type String and assign it your first name.
  2. Declare a mutable variable age of type Int and assign it your age.
  3. Change the value of age to a different number.
// Solution
val firstName: String = "John"
var age: Int = 25
age = 26

Exercise 2: Work with Nullable Types

  1. Declare a nullable variable middleName of type String? and assign it a value.
  2. Use the safe call operator to print the length of middleName.
  3. Use the Elvis operator to provide a default value if middleName is null.
// Solution
var middleName: String? = "Michael"
println(middleName?.length) // Safe call
println(middleName?.length ?: 0) // Elvis operator

Summary

In this section, we covered the basics of variables and data types in Kotlin. We learned about immutable (val) and mutable (var) variables, primitive and non-primitive data types, type inference, and nullable types. These concepts are fundamental to writing Kotlin programs and will be used extensively in subsequent modules.

© Copyright 2024. All rights reserved