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

How to declare an extension val for Any type in Kotlin

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

当我扩展一个函数时它工作正常,

fun Any.getClassTag(): String { return this::class.java.simpleName }

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

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

Function declaration must have a name

如何处理?

您正在创建一个扩展 属性,就像它是一个函数一样。创建扩展 属性 的正确方法是定义属性的 get 和 set 方法。这是你应该做的:

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

Kotlin Playground Example

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

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

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

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

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

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

因此,为扩展 属性 提供价值的唯一方法是明确提供 getters/setters.

在您的情况下,应该如下所示:

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

检查这个Extension 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