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

Viewed 311

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.

3 Answers

Reflection is a language's ability to inspect and dynamically call classes, methods, attributes, etc. at runtime.

Reflections can't be used at compile-time, they are only available at the runtime, so you can't use either of ::class or ::class.java, they won't be available at the compile-time.

The const modifier marks the val a compile-time constant. Hence can't call any runtime functions at compile-time.

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

const keyword is used to define compile-time constants but val can have runtime constants. simplename is not available at compile time hence the error.

Related