Saturday 23 December 2017

Kotlin: const vs val

'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.

Find the below working application.

HelloWorld.kt
const val VENDOR_NAME = "Self Learning Java blog"
val PICon = getPI()

fun getPI(): Double {
 return 3.14
}

fun main(args: Array<String>) {
 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

1 comment: