CS Electrical And Electronics
@cselectricalandelectronics

What is val in Kotlin and when to use it?

All QuestionsCategory: KotlinWhat is val in Kotlin and when to use it?
chetan shidling asked 3 years ago

I need short information.

1 Answers
chetan shidling answered 3 years ago

Val is used when you want to save the constant value. 
 
class chetanhotel
{
val name : String = “”;
}
fun main(args: Array<String>){
println(“Hello Customers”)

var customer = chetanhotel();
customer.name = “Chetan”;
println(“My name is : “+ customer.name)
//Other method
println(“My name is : ${customer.name}”)
}
 
Output:
 
Val cannot be reassigned.
 
This code will give an error, we can’t change the name using val. But we can change by using var, see the below code.
 
class chetanhotel
{
var name : String = “”;
}
fun main(args: Array<String>){
println(“Hello Customers”)

var customer = chetanhotel();
customer.name = “Chetan”;
println(“My name is : “+ customer.name)
//Other method
println(“My name is : ${customer.name}”)
}
 
Output:
 
Hello Customers
My name is : Chetan
My name is : Chetan