Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to declare an extension val for Any type in Kotlin

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?

like image 913
Sazzad Hissain Khan Avatar asked Oct 16 '25 19:10

Sazzad Hissain Khan


2 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.

like image 192
tynn Avatar answered Oct 19 '25 09:10

tynn


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

like image 45
Jian Astrero Avatar answered Oct 19 '25 09:10

Jian Astrero