The Val keyword is used to declare a new variable with kotlin not in Python. It is like ‘var‘, however in this case the variable cannot be reused.
Val is immutable. Once assigned the Val becomes read-only, however, the properties of a val object could be changed, but the object itself is read-only.
Note: there is no in built equivalent fucntion for Val() in Python
Val keyword in Python
Simple example code.
fun main()
{
val marks = 10
println("Previous marks is " + marks)
marks = 30
println("new marks " + marks)
}
Output: Val cannot be reassigned
// Changing values of val object
fun main()
{
val book = Book("Java", 1000)
println(book)
book.name = "Kotlin"
println(book)
}
data class Book(var name : String = "",
var price : Int = 0)
Output:
Book(name=Java, price=1000)
Book(name=Kotlin, price=1000)
Do comment if you have any doubts or suggestions on this Python keywords topic.
Note: IDE: PyCharm 2021.3.3 (Community Edition)
Windows 10
Python 3.10.1
All Python Examples are in Python 3, so Maybe its different from python 2 or upgraded versions.