Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why MyClass::class.java.simpleName can't be constant value?

Tags:

kotlin

A normal val is OK, and is initialized.

class MyClass {
    companion object {
        private val TAG = MyClass::class.java.simpleName
    }
}

But const val causes compilation error.

class MyClass {
    companion object {
        private const val TAG = MyClass::class.java.simpleName
    }
}

error log

MyClass.kt:27:33: error: const 'val' initializer should be a constant value
        private const val TAG = MyClass::class.java.simpleName

It seems unintuitive that simpleName cannot be defined as a const val.

like image 919
user3752013 Avatar asked Oct 23 '25 13:10

user3752013


1 Answers

In Kotlin, the const keyword should only be used when the value is a compile-time constant. Here MyClass::class.java.simpleName is not a compile-time constant. so we need to use val instead of const. val is same as the final keyword in Java.

For more info on this, please check here

like image 65
Shalu T D Avatar answered Oct 27 '25 03:10

Shalu T D