如何在 Kotlin 中为 Any 类型声明扩展 val

Saz*_*han 4 inheritance extension-methods android dependency-properties kotlin

据我所知,类型Any类似于Kotlin默认情况Objectjava由我们声明的任何类实现的类型。我想将类名扩展为新的val classTag. 因此,

当我扩展一个函数时它工作得很好,

fun Any.getClassTag(): String { return this::class.java.simpleName }
Run Code Online (Sandbox Code Playgroud)

但是当我扩展val类型时,我发现编译器会出错。

val Any.classTag: String { return this::class.java.simpleName }
Run Code Online (Sandbox Code Playgroud)

函数声明必须有名称

该怎么处理呢?

tyn*_*ynn 7

在这一行中你会遇到几个错误:

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
Run Code Online (Sandbox Code Playgroud)

这是因为您没有正确声明访问器:

val Any.classTag: String get() { return this::class.java.simpleName }
Run Code Online (Sandbox Code Playgroud)

get()您只需在块之前添加访问器即可。