1.

How are variables declared in Kotlin? What are the different types of variables in Kotlin? Explain with examples.

Answer»

Every variable in Kotlin must be declared before it can be USED. An attempt to use a variable without declaring it results in a syntax error. The type of data you are authorised to put in the memory ADDRESS is determined by the variable type declaration. The type of variable can be determined from the initialised value in the case of local variables.

For example,

var site = "interviewbit"

The above code declares a variable “site” of type String because the value with which the variable is initialised is a String.

There are broadly two types of variables in Kotlin. They are as follows:-

  • Immutable Variables — Immutable variables are also known as read-only variables. They are declared using the val keyword. Once these variables have been declared, we cannot change their values.

The syntax is as follows :

val variableName = value

For example,

val sample = "interview"sample = "interviewbit" // results in compile time error

The second line in the above code SNIPPET would RESULT in a compile-time error as expected.

Because it can be initialized with the value of a variable, an immutable variable is not a constant. It means that the value of an immutable variable does not need to be known at compile-time and that if it is defined inside a construct that is called several times, it can take on a different value with each function call. For example, 

var sample = "interview"val newSample = sample // no compile time error

The above code snippet runs fine and does not produce any errors.

  • Mutable Variables - In a mutable variable, the value of the variable can be changed. We use the keyword “var” to declare such variables.

The syntax is as follows :

var variableName = value

For example,

var sample = "interview"sample = "FUN" // no compile time error

The above code snippet runs fine and does not produce any errors.



Discussion

No Comment Found