InterviewSolution
| 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:-
The syntax is as follows : val variableName = valueFor example, val sample = "interview"sample = "interviewbit" // results in compile time errorThe 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 errorThe above code snippet runs fine and does not produce any errors.
The syntax is as follows : var variableName = valueFor example, var sample = "interview"sample = "FUN" // no compile time errorThe above code snippet runs fine and does not produce any errors. |
|