How to Declare Variables In Kotlin?

11 minutes read

To declare variables in Kotlin, you can use the var or val keywords along with the name of the variable and its data type. Here's the syntax:

1
2
var variableName: DataType
val constantName: DataType


  • The var keyword is used to declare mutable variables whose values can be changed later.
  • The val keyword is used to declare read-only variables, also known as constants, whose values cannot be changed after assignment.


You can specify the data type explicitly, or you can rely on type inference to infer the data type based on the assigned value. For example:

1
2
var myVariable: Int = 10
val myConstant = "Hello"


Here, the variable myVariable is explicitly declared as an Int and assigned a value of 10. On the other hand, the constant myConstant is not explicitly declared with a data type since the Kotlin compiler can infer that it's a String based on the assigned value "Hello".


You can also declare multiple variables of the same type in a single line using a comma-separated list:

1
2
var age: Int = 25
var name, city: String = "John", "New York"


In this example, the variables name and city are declared together in a single line and are both inferred as String type.


It is worth mentioning that Kotlin supports type inference, meaning you can omit the data type altogether when it can be inferred from the assigned value. For example:

1
2
var x = 5 // The type Int is inferred
val pi = 3.14 // The type Double is inferred


In the above code snippets, the data types are not explicitly mentioned as Kotlin can automatically infer them.

Best Kotlin Books to Read in 2024

1
Atomic Kotlin

Rating is 5 out of 5

Atomic Kotlin

2
Kotlin Cookbook: A Problem-Focused Approach

Rating is 4.9 out of 5

Kotlin Cookbook: A Problem-Focused Approach

3
Head First Kotlin: A Brain-Friendly Guide

Rating is 4.8 out of 5

Head First Kotlin: A Brain-Friendly Guide

4
Kotlin in Action

Rating is 4.7 out of 5

Kotlin in Action

5
Kotlin In-Depth: A Guide to a Multipurpose Programming Language for Server-Side, Front-End, Android, and Multiplatform Mobile (English Edition)

Rating is 4.6 out of 5

Kotlin In-Depth: A Guide to a Multipurpose Programming Language for Server-Side, Front-End, Android, and Multiplatform Mobile (English Edition)

6
Kotlin Design Patterns and Best Practices: Build scalable applications using traditional, reactive, and concurrent design patterns in Kotlin, 2nd Edition

Rating is 4.5 out of 5

Kotlin Design Patterns and Best Practices: Build scalable applications using traditional, reactive, and concurrent design patterns in Kotlin, 2nd Edition

7
Kotlin Programming: The Big Nerd Ranch Guide (Big Nerd Ranch Guides)

Rating is 4.4 out of 5

Kotlin Programming: The Big Nerd Ranch Guide (Big Nerd Ranch Guides)

8
Java to Kotlin

Rating is 4.2 out of 5

Java to Kotlin

9
Kotlin Essentials (Kotlin for Developers)

Rating is 4.1 out of 5

Kotlin Essentials (Kotlin for Developers)


How to declare a variable of custom data type in Kotlin?

In Kotlin, you can declare a variable of a custom data type using the val keyword for read-only variables or var keyword for mutable variables, followed by the variable name, a colon, and the custom data type.


Here's an example of declaring a variable of a custom data type in Kotlin:

1
2
3
4
5
6
class Person(val name: String, val age: Int)

fun main() {
    val person: Person = Person("John Doe", 25)
    println("${person.name} is ${person.age} years old.")
}


In the example above, we've created a custom data type Person with name and age properties. In the main function, we declare a variable person of type Person and initialize it with a new instance of the Person class. We can then access the properties of the person object using dot notation.


How to declare multiple variables in one line in Kotlin?

In Kotlin, you can declare multiple variables in one line using the destructuring declaration syntax.


Here's an example:

1
val (firstName, lastName, age) = Triple("John", "Doe", 30)


In the above example, we have declared three variables (firstName, lastName, and age) in a single line using the val keyword. The values are assigned using the Triple class constructor.


You can also declare multiple variables of the same type in one line using the var keyword:

1
var (x, y, z) = Triple(1, 2, 3)


In this example, we are declaring three variables (x, y, and z) in a single line, and they are assigned values using the Triple constructor.


You can use the destructuring declaration syntax with various types and classes, such as Pair, Array, or custom data classes.


What is variable declaration in Kotlin?

Variable declaration in Kotlin is the process of creating a variable and optionally assigning it a value. It involves specifying the name of the variable, its type, and an optional initial value.


In Kotlin, variable declaration can be done using the var or val keywords. The var keyword is used to declare a mutable variable, which means its value can be changed. On the other hand, the val keyword is used to declare an immutable variable, which means its value cannot be changed once it is assigned.


Example of variable declaration in Kotlin:

1
2
var age: Int = 25      // mutable variable declaration with type Int and initial value 25
val name: String = "John"  // immutable variable declaration with type String and initial value "John"


In the above example, age is a mutable variable of type Int, and name is an immutable variable of type String. The age variable can be reassigned a new value later in the program, whereas the name variable's value remains unchanged throughout the program.


How to declare a variable as a top-level property in Kotlin?

In Kotlin, a top-level property is declared outside of any class or function. To declare a variable as a top-level property in Kotlin, you can follow these steps:


Step 1: Create a new Kotlin file or open an existing Kotlin file.


Step 2: Declare the variable outside of any class or function, on the top-level scope of the file.


Step 3: Assign a value to the variable.


Step 4 (optional): Provide an explicit type for the variable, if needed.


Here's an example:

1
2
3
// MyTopLevelProperty.kt

val myTopLevelProperty: String = "Hello, World!"


In the example above, the variable myTopLevelProperty is declared as a top-level property. It is assigned the value "Hello, World!" with an explicit type of String.


You can now access this variable from other parts of your code, regardless of any specific class or function.


How to initialize a variable later in Kotlin?

In Kotlin, if you want to declare a variable without initializing it immediately, you can use the lateinit keyword. This allows you to initialize the variable at a later point in your code. Follow these steps:

  1. Declare the variable without initializing it:
1
lateinit var variableName: DataType


  1. Later in your code, initialize the variable before using it:
1
variableName = value


Here's an example where a lateinit variable of type String is initialized later:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
lateinit var message: String

fun main() {
    // The variable is declared but not assigned a value yet

    // Initializing the variable
    message = "Hello, World!"

    // Using the variable
    println(message)
}


Note that lateinit can only be used with mutable properties, i.e., var, and not with val (immutable) properties. It should also be ensured that the lateinit variable is actually initialized before accessing it; otherwise, a lateinit property has not been initialized exception will be thrown at runtime.

Facebook Twitter LinkedIn Telegram Whatsapp Pocket

Related Posts:

Working with Android extensions in Kotlin allows you to leverage the power of Kotlin's extension functions to easily enhance the functionality of Android classes. Here's how you can work with Android extensions in Kotlin.To create an Android extension,...
To run Kotlin on Ubuntu, you can follow these steps:Install Java Development Kit (JDK): Since Kotlin runs on the Java Virtual Machine (JVM), you need to have Java installed on your system. Open a terminal and run the following command to install the default JD...
To use a Kotlin function in Java, you can follow these steps:Create a Kotlin function that you want to use in Java. For example, let's consider a simple function named printMessage() that prints a message. fun printMessage() { println("Hello, world...
In Erlang, variables are declared using a pattern-matching syntax. The process involves assigning values to variables and extracting values from complex data structures. Here is how you can declare variables in Erlang:Simple Variable Declaration: To declare a ...
The Kotlin Standard Library functions are a collection of commonly used extension functions and top-level functions provided by the Kotlin programming language. These functions aim to simplify and enhance the development process by offering a set of utility fu...
In order to call a top-level Kotlin function in Java, you need to follow the steps below:Ensure that the Kotlin function is defined as a top-level function, which means it is not nested inside any class or object. Import the necessary Kotlin dependencies in yo...