Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

variables
kotlin
communitycreator

How to create variables in Kotlin

Programming Bytes

In Kotlin, we can declare variables in two ways:

1. Using the val keyword

The variable declared using the val keyword is immutablevalue cannot be changed. We can’t reassign a value to a variable that was declared using val as attempting to do so will throw an error.

val company = "Educative";

Above, we have declared the company variable. We don’t need to explicitly declare the data type for the company variable as Kotlin implicitly does this from the initializer expression. For example, if we have assigned “Educative” to the company variable, Kotlin will internally find the type and use that type for that variable.

Regardless, we are not restricted to specifying the data type of the variable. We can specify the data type by using:

var company:String = "Educative"

We will get an error when we try to re-assign the value of a variable created using val:

 val day = "sunday"
 day = "Monday";

// Val cannot be reassigned

2. Using var keyword

The variable declared using var keyword is mutablethe value can be changed.

var company:String = "Educative"
company = "Educative.io"

Suppose we have created a variable:

var company = "Educative"

Kotlin will internally assign the company as String type. When we re-assign other type values to the company variable, it will result in an error:

var company = "Educative"
company = 10 // The integer literal does not conform to the expected type String

Declaring variable without initial value

Declaring a variable using var without an initializer:

var company // Error: The variable must either have a Type annotation or be initialized

The above variable declaration will throw an error because Kotlin doesn’t know the data type to be assigned to the company variable.

To resolve the above error, we can specify the type of the variable during the declaration and assign the value later.

fun main() {
    val day = "sunday"
    val mood:String
    if( day.equals("sunday") ) {
      mood = "Happy"
    } else {
      mood = "Neutral"
    }
    println(mood)
}

In the above code, we have declared the mood variable using val with type String and assigned the value to it inside the if...else block.

RELATED TAGS

variables
kotlin
communitycreator
RELATED COURSES

View all Courses

Keep Exploring