Kotlin Tutoial
Basics
Control Flow
Array & String
Functions
Collections
OOPs Concept
Exception Handling
Null Safety
Regex & Ranges
Java Interoperability
Miscellaneous
Android
In Kotlin, variables are a fundamental concept. They allow you to store and manipulate data in your programs. This tutorial will cover the basics of declaring and using variables in Kotlin.
Kotlin provides two main keywords for declaring variables:
val
: Declares a read-only (immutable) variable. Once you assign a value to it, you can't change it.var
: Declares a mutable variable. You can change its value as needed.Using val
(Immutable Variable)
val pi: Double = 3.14 // pi = 3.14159 // This will cause a compilation error since pi is immutable
Using var
(Mutable Variable)
var count: Int = 10 count = 11 // This is allowed since count is mutable
In the examples above, we explicitly mentioned the type of the variable (Double
and Int
). However, Kotlin has a powerful type inference mechanism, so you often don't need to explicitly state the type:
val name = "Alice" // The compiler knows this is a String var age = 30 // The compiler knows this is an Int
In some scenarios, you might not be able to initialize a variable immediately. For these cases, Kotlin provides the lateinit
keyword for var
variables. This is commonly used in Android development when initializing views:
lateinit var username: String
Note: Make sure to initialize lateinit
variables before using them; otherwise, you'll encounter a runtime exception.
Kotlin emphasizes null safety. By default, variables cannot hold a null value. If you want a variable to be nullable, you can denote its type with a ?
:
var nullableString: String? = null
by lazy
DelegateSometimes you might want a read-only variable to be computed only upon its first access. This is particularly useful for expensive computations:
val lazyValue: String by lazy { println("Computed!") "Hello, World!" } println(lazyValue) // Will print "Computed!" followed by "Hello, World!" println(lazyValue) // Will only print "Hello, World!"
Once you've declared variables, you can perform operations:
var a = 5 var b = 3 var sum = a + b
Variables are at the core of any programming language, and Kotlin offers a versatile set of tools for variable declaration and manipulation. Emphasizing immutability with val
, ensuring null safety, and supporting late initialization are some of the features that make Kotlin stand out when working with variables.
In Kotlin, you can declare variables using the val
and var
keywords. The syntax is straightforward:
fun main() { val immutableVariable = 42 // Immutable variable (read-only) var mutableVariable = "Hello" // Mutable variable println(immutableVariable) println(mutableVariable) }
val
vs var
:val
is used for immutable (read-only) variables. Once assigned, their values cannot be changed.var
is used for mutable variables. You can reassign values to them.fun main() { val immutableVariable = 42 var mutableVariable = "Hello" // immutableVariable = 24 // Error: Val cannot be reassigned mutableVariable = "World" println(immutableVariable) println(mutableVariable) }
Immutable variables (val
) are read-only and cannot be reassigned after initialization, providing safety and avoiding accidental changes. Mutable variables (var
) allow reassignment.
fun main() { val immutableVariable = 42 var mutableVariable = "Hello" // immutableVariable = 24 // Error: Val cannot be reassigned mutableVariable = "World" println(immutableVariable) println(mutableVariable) }
Kotlin supports type inference, allowing the compiler to automatically determine the variable type based on its initialization:
fun main() { val number = 42 // Type inferred as Int val message = "Hello" // Type inferred as String println(number) println(message) }
While Kotlin supports type inference, you can also explicitly specify variable types:
fun main() { val number: Int = 42 val message: String = "Hello" println(number) println(message) }
Mutable variables (var
) can be reassigned with a new value:
fun main() { var mutableVariable = "Hello" println(mutableVariable) mutableVariable = "World" println(mutableVariable) }
Variables in Kotlin are non-nullable by default. To allow null values, you need to explicitly specify the type as nullable using the ?
:
fun main() { var nullableVariable: String? = null // nullableVariable = "Hello" // Uncommenting this line would be valid println(nullableVariable) }
You can use the lazy
delegate for lazy initialization of variables, meaning the variable will only be computed the first time it's accessed:
fun main() { val lazyVariable: String by lazy { println("Initializing lazy variable") "Hello Lazy" } println("Before accessing lazy variable") println(lazyVariable) }
Delegated properties allow you to define custom behavior for property access and modification. Here's a simple example using the by
keyword:
class DelegateExample { var delegatedVariable: String by CustomDelegate() fun printVariable() { println(delegatedVariable) } } class CustomDelegate { operator fun getValue(thisRef: Any?, property: KProperty<*>): String { return "Delegated Value" } operator fun setValue(thisRef: Any?, property: KProperty<*>, value: String) { // Custom logic for setting the value println("Setting value to: $value") } } fun main() { val example = DelegateExample() example.printVariable() example.delegatedVariable = "New Value" example.printVariable() }
lateinit
for late-initialized variables in Kotlin:The lateinit
keyword allows you to declare a non-null variable that will be initialized later:
class LateInitExample { lateinit var lateInitVariable: String fun initialize() { lateInitVariable = "Initialized Late" } fun printVariable() { println(lateInitVariable) } } fun main() { val example = LateInitExample() // example.printVariable() // Uncommenting this line would result in an UninitializedPropertyAccessException example.initialize() example.printVariable() }
Constants are declared using the const
keyword, and read-only variables are declared using val
. Constants must be top-level or in an object declaration and have a primitive type or a String:
const val PI = 3.14 fun main() { val readOnlyVariable = "Read Only" println(PI) println(readOnlyVariable) }
You can use visibility modifiers like private
, protected
, internal
, and public
to control the visibility of variables:
class VisibilityExample { private var privateVariable = "Private" internal var internalVariable = "Internal" protected var protectedVariable = "Protected" var publicVariable = "Public" } fun main() { val example = VisibilityExample() // Accessing publicVariable is allowed println(example.publicVariable) // Uncommenting the lines below would result in compile-time errors // println(example.privateVariable) // println(example.internalVariable) // println(example.protectedVariable) }