Get Even More Visitors To Your Blog, Upgrade To A Business Listing >>

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.

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")

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

Share the post

Kotlin: const vs val


Subscribe to Java Tutorial : Blog To Learn Java Programming

Get updates delivered right to your inbox!

Thank you for your subscription