Kotlin Variables: Types, Examples, Declare, var vs val
What is Kotlin Variable?
A Kotlin variable is an integral part of programming. It is a name that represents computer memory locations that store values in a computer program and use the names later to retrieve the stored values to be used in a program.
We can create Kotlin arrays by using var or val keywords and use an equal sign = to assign a value to the created variables.
You need to declare the Kotlin variable before using it. If a variable is not declared, any attempt to use the variable will give a syntax error. Moreover, declaring a variable type decides the type of data you can store in the memory location. For local variables, the variable type can be inferred from the initialized value.
Types of Variables in Kotlin Language
Here are the main types of variables in Kotlin:
-
Immutable Variables (val):
These are declared using the val keyword. Immutable variables cannot be reassigned after their initial value is assigned. They are similar to constants in other programming languages. Once you assign a value to a val variable, you cannot change it.
val pi = 3.14159
-
Mutable Variables (var):
These are declared using the var keyword. Mutable variables can be reassigned after their initial value is assigned. You can change the value of a var variable as many times as needed during its scope.
var count = 10
count = 20 // Valid, reassigning the value
-
Type Inference:
Kotlin allows you to omit the explicit type declaration for variables in many cases because it can infer the type from the assigned value. For example:
val message = "Hello, Kotlin!" // Type of message is inferred as String
var number = 42 // Type of number is inferred as Int
-
Explicit Type Declaration:
You can also explicitly specify the type of a variable when declaring it:
val name: String = "Alice"
var age: Int = 30
-
Nullable Variables:
In Kotlin, by default, variables cannot hold null values. If you want a variable to be nullable, you can indicate this by appending a ? to the type:
val nullableName: String? = null
-
Late-Initialized Variables:
When working with properties in classes, you can declare them as lateinit to indicate that they will be initialized at a later point, before their first use. This is particularly useful for non-nullable properties that cannot be initialized in the constructor.
lateinit var someValue: String
// ... later in the code
someValue = "Initialized value"
-
Top-Level Variables:
Variables can be declared at the top level of a Kotlin file or within a function. They can be accessed from anywhere in the file or function where they are defined.
How to Declare a Variable in Kotlin?
You can declare variables in Kotlin using the val and var keywords, depending on whether you want the variable to be immutable (unchangeable) or mutable (changeable), respectively.
Here's how you can declare variables in Kotlin:
-
Using Kotlin val
Use the val keyword in Kotlin to declare an immutable variable. Once you assign a value to a val variable, you cannot change it.
Example:
val pi = 3.14159 // Immutable variable
val name = "Alice" // Immutable variable
val age = 30 // Immutable variable
// Attempting to reassign a value to a val variable will result in a compilation error.
// pi = 3.14 // Error: Val cannot be reassigned.
In the above code, pi, name, and age are declared as val variables, which means their values cannot be changed once assigned.
-
Using Kotlin var
Use the var keyword in Kotlin to declare a mutable variable. You can change the value of a var variable after it's initially assigned.
Example:
var count = 10 // Mutable variable
var message = "Hello, Kotlin!" // Mutable variable
count = 20 // Valid, reassigning the value
message = "Greetings, Kotlin!" // Valid, changing the value
In this example, count and message are declared as var variables, which means their values can be changed or reassigned after the initial assignment.
Kotlin var vs val (Difference)
Here's a comparison between var and val in Kotlin to understand the differences between the two:
Scope of a Kotlin Variable
A variable in Kotlin exists only within the block of code ( {………….} ), where it is declared. We can’t access the variable outside the loop.
The same variable can be declared inside the nested loop. This means that if a function includes an argument x and we declare a new variable x within the same loop, the x inside the loop will be different from the one in the argument.
The scope of a Kotlin variable defines where in your code the variable can be accessed or used. The scope of a variable is determined by where it is declared, and it can vary depending on the context in which the variable is defined.
Here are some common scopes for Kotlin variables:
-
Block Scope
Variables declared within a block of code (enclosed in curly braces) have a scope limited to that block. They are only accessible within the block and any nested blocks.
fun someFunction() {
if (condition) {
val localVar = 42 // Block-scoped variable
// localVar is accessible within this if block
}
// localVar is not accessible here
}
-
Function Scope:
Variables declared as function parameters or local variables within a function are scoped to that function. They are accessible anywhere within that function.
fun calculateSum(a: Int, b: Int): Int { // a and b have function scope
val result = a + b // result has function scope
return result
}
-
Class Scope:
Variables declared within a class, but outside of any functions or blocks, are scoped to the entire class. They are accessible by all member functions and properties within that class.
class MyClass {
val classVariable = "I belong to the class" // Class-scoped variable
fun printMessage() {
println(classVariable) // Accessing classVariable within the function
}
}
-
Object Scope:
Variables declared within an object or a companion object have a scope limited to that object or companion object. They are accessible using the object's or companion object's name.
object MyObject {
val objectVariable = "I belong to the object" // Object-scoped variable
}
class MyClass {
companion object {
val companionVariable = "I belong to the companion object" // Companion object-scoped variable
}
}
-
Package Scope:
Variables declared at the top level of a Kotlin file have a scope that is effectively package-level. They are accessible from other Kotlin files within the same package.
// In File1.kt
val packageScopedVar = "I am in File1"
// In File2.kt (in the same package)
fun printPackageScopedVar() {
println(packageScopedVar) // Accessing packageScopedVar from another file in the same package
}
-
Global Scope:
Variables declared outside of any class, function, or object have a global scope and can be accessed from anywhere within the current module or project. However, it's generally a good practice to limit the use of global variables.
val globalVariable = "I am a global variable" // Global-scoped variable
fun main() {
println(globalVariable) // Accessing globalVariable from the main function
}
Naming Convention of Kotlin Variables
In Kotlin, variable naming conventions are important for writing clean and readable code. The naming conventions are not enforced by the language itself, but they are widely followed by the Kotlin community to ensure code consistency.
Here are some common naming conventions for variables in Kotlin:
1. CamelCase:
Variables should be named in CamelCase, which means starting with a lowercase letter and capitalizing the first letter of each subsequent word in the variable name.
For example:
-
userName
-
itemPrice
-
numberOfApples
2. Use Descriptive Names
Variable names should be meaningful and describe the purpose of the variable. Avoid using single-character or cryptic names like x, y, or tmp. Instead, use descriptive names that make the code more self-explanatory.
-
Good: totalPrice
-
Bad: t
3. Use English Words:
Kotlin variable names should be in English to maintain consistency and make the code understandable to a broader audience.
-
Good: customerName
-
Bad: nomClient (Non-English variable names)
4. Avoid Abbreviations:
While shortening variable names can save typing, it can also reduce code readability. Avoid excessive abbreviations and opt for full, descriptive names whenever possible.
-
Good: maximumValue
-
Bad: maxVal
5. Prefixes and Suffixes:
Sometimes, it's helpful to add prefixes or suffixes to variable names to provide context.
For example:
-
isReady (a Boolean variable with a prefix)
-
countOfItems (a variable with a suffix)
6. Constants:
For constants (values that don't change and are typically declared using val), use uppercase letters with underscores to separate words. This convention is similar to the way constants are named in Java.
-
PI (constant representing π)
-
MAX_VALUE (constant representing a maximum value)
7. Packages and Imports:
When using package-level constants or top-level functions, use lowercase letters and underscores to separate words in the package or function name.
-
com.example.util
-
import com.example.util.myFunction
8. Classes and Types:
Class names and type names should be in CamelCase and start with an uppercase letter.
-
Person
-
ProductCategory
9. Enums:
Enum constants should be in uppercase letters with underscores separating words.
-
enum class Color { RED, GREEN, BLUE }
10. Nullable Types:
For variables that can hold null, it's a good practice to indicate it in the name. This is often done by adding a nullable suffix or using a more descriptive name.
-
customerNameNullable or nullableCustomerName
Remember that consistency is key. When working on a team or contributing to open-source projects, it's important to follow the established naming conventions to maintain code readability and collaboration.
Kotlin Basic Variable Types
Kotlin is a statically typed language, so a variable type is known during the compile time.
val language: Int
val marks = 12.3
Here, the Kotlin compiler is certain that the language is Int type and marks is double data type before the compile time.
The built-in types in Kotlin can be divided into the following categories:
1. Numbers
In Kotlin, numbers are similar to Java. The following 6 built-in data types represent numbers.
-
Byte
The byte data type has values from -128 to 127. We use but instead of Int data types to save memory when we know that the value of a variable will be within [-128, 127].
-
Short
The short data type has values from -32768 to 32767. We use short data type rather than other integer data types to save memory when we are sure that the value of the variable will be within [-32768, 32767].
-
Int
The Int data type has values from -231 to 231-1.
-
Long
This data type can have values from -263 to 263-1.
-
Float
The float data type refers to a single-precision 32-bit floating point.
-
Double
This data type is a double-recision 64-bit floating point.
Example:
val age: Int = 30
val pi: Double = 3.14159
In this example, age is an integer variable, and pi is a double-precision floating-point variable.
2. Char
Char data types are used to represent a character in Kotlin.
Unlike Java, the Char data type cannot be treated as numbers.
Example:
val grade: Char = 'A'
Here, grade is a character variable holding the value 'A'.
3. Boolean
The boolean data type has two possible values- true or false.
val isStudent: Boolean = true
val hasPermission: Boolean = false
These variables, isStudent and hasPermission, are boolean variables representing true and false values, respectively.
4. Kotlin Arrays
A Kotlin array refers to a container holding data of one type. For example, an array holding 100 values of int type. The array class represents arrays. Also, a class has get/set functions, size property, and other useful member functions.
Example:
val numbers: IntArray = intArrayOf(1, 2, 3, 4, 5)
numbers is an integer array containing five elements.
5. Kotlin Strings
In Kotlin, the string class represents strings. The string literals like “this is a string" is implemented as an instance of this class.
Example:
val greeting: String = "Hello, Kotlin!"
val username: String? = null // Nullable string
greeting is a string variable containing a greeting message, and username is a nullable string that can hold a string value or be null.
Get Type of Variable in Kotlin
In Kotlin, you can get the type of a variable or expression using the ::class property or the ::class.java property, depending on whether you need the Kotlin class or the Java class.
Here's how you can do it:
-
Using ::class (Kotlin Class)
To get the Kotlin class of a variable or expression, you can use the ::class property:
val name = "Alice"
val type = name::class
println("Type of 'name' is: $type")
In this example, type will hold the Kotlin class, and you can access its properties and methods.
-
Using ::class.java (Java Class)
To get the Java class of a variable or expression, you can use the ::class.java property:
val name = "Alice"
val type = name::class.java
println("Java Type of 'name' is: $type")
In this case, type will hold the Java class, which can be useful when working with Java libraries or reflection.
Kotlin Environment Variables
In Kotlin, you can access environment variables using the System.getenv() function, which allows you to retrieve the values of environment variables set on your system. Environment variables are commonly used to store configuration information or sensitive data that should not be hard-coded in your application.
Here's how you can use System.getenv() to access environment variables in Kotlin:
fun main() {
// Retrieve the value of an environment variable named "MY_VARIABLE"
val myVariable = System.getenv("MY_VARIABLE")
if (myVariable != null) {
println("Value of MY_VARIABLE: $myVariable")
} else {
println("MY_VARIABLE is not set.")
}
}
In the code above:
-
We use System.getenv("MY_VARIABLE") to retrieve the value of the environment variable named "MY_VARIABLE."
-
If the environment variable is set, its value will be stored in the myVariable variable, and we can then use it as needed.
-
If the environment variable is not set, System.getenv("MY_VARIABLE") will return null, and we handle this case by checking if myVariable is not null.
-
Before running your Kotlin program, make sure that the environment variable you're trying to access is set on your system. The process for setting environment variables varies depending on your operating system (e.g., in Windows, you can set environment variables in the system properties; in Linux or macOS, you can use the export command).
Kotlin Class Variable
Class variables in Kotlin are often referred to as "properties." Properties in Kotlin are similar to fields or instance variables in other programming languages. They are variables associated with a class and can be used to store and manage data within objects of that class.
Here's how you can declare and use class properties (variables) in Kotlin:
class Person {
// Property declaration
var name: String = ""
var age: Int = 0
// Member function
fun introduce() {
println("Hello, my name is $name, and I am $age years old.")
}
}
fun main() {
// Creating an instance of the Person class
val person = Person()
// Accessing and modifying class properties
person.name = "Alice"
person.age = 30
// Calling a member function
person.introduce()
}
In the example above:
We declare a Person class with two properties: name and age. These properties have default values of an empty string and zero, respectively.
Inside the introduce member function, we access the name and age properties to display information about the person.
In the main function, we create an instance of the Person class using val person = Person(). We then set the values of the name and age properties using the dot notation (person.name and person.age).
Finally, we call the introduce member function on the person object to print out the person's information.
Class variables in Kotlin can also have custom getters and setters, allowing you to control the behavior when getting or setting their values. Additionally, Kotlin supports read-only properties (declared with val), which can only be assigned a value during object initialization and cannot be modified afterward.