'const' keyword is used to Define compile time constants,I.e, the value of the Const variable is known at compile time. Whereas ‘val’ is used to define constants at run time.
For example, you can’t define a const like below.
const val PICon = getPI()
When you try to compile the kotlin program with above statement, you will endup in below error.
‘Const 'val' has type 'Unit'. Only primitives and String are allowed’.
This is because, getPI() is evaluated at run time and assign the value to PICon, but const is used to define the constant at compile time.
‘Const 'val' has type 'Unit'. Only primitives and String are allowed’.
This is because, getPI() is evaluated at run time and assign the value to PICon, but const is used to define the constant at compile time.
Find the below working application.
const val VENDOR_NAME = "Self Learning Java blog"
val PICon = getPI()
fun getPI(): Double {
return 3.14
}
fun main(args: Array) {
println("Vendor Name $VENDOR_NAME")
println("Value of PI : $PICon")
}
Output
Vendor Name Self Learning Java blog
Value of PI : 3.14
Previous Next Home
This post first appeared on Java Tutorial : Blog To Learn Java Programming, please read the originial post: here