How to declare an extension val for Any type in Kotlin

Viewed 1628

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?

4 Answers

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

According to Kotlin Docs, Initializers are not allowed for extension properties.

So, only way to provide value to extension property is by explicitly providing getters/setters.

In your case, it should be like below :

val Any.classTag: String 
    get() { 
        return this::class.java.simpleName
    }

Check thisExtension Properties

Note that, since extensions do not actually insert members into classes, there's no efficient way for an extension property to have a backing field. This is why initializers are not allowed for extension properties. Their behavior can only be defined by explicitly providing getters/setters.

val Any.classTag: String  get() = this::class.java.simpleName
Related