As I know type Any
in Kotlin
is similar to Object
in java
which by default is implemented by any class we declare. I want to extend the class name into a new val
classTag
. Thus,
When I extend a function it works fine,
fun Any.getClassTag(): String { return this::class.java.simpleName }
But I found compilers error in case when I extend a val
type.
val Any.classTag: String { return this::class.java.simpleName }
Function declaration must have a name
How to deal with that?
You'll have several errors in this one line:
Error:(1, 0) Extension property must have accessors or be abstract
Error:(1, 23) Property getter or setter expected
Error:(1, 24) Expecting a top level declaration
Error:(1, 25) Function declaration must have a name
Error:(1, 34) 'this' is not defined in this context
This is, because you didn't declare the accessors properly:
val Any.classTag: String get() { return this::class.java.simpleName }
You only need to add the get()
accessor just before your block.
You are creating an extension property as if it's a function. The right way to create an extension property is to define the properties' get and set methods. here is what you should've done:
val Any.classTag: String
get() = this::class.java.simpleName
Kotlin Playground Example
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With