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

标签 android inheritance kotlin extension-methods dependency-properties

据我所知,键入 AnyKotlin类似于 Objectjava默认情况下,它由我们声明的任何类实现。我想把类名扩展成一个新的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



如何处理?

最佳答案

您将在这一行中遇到几个错误:

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()访问器就在您的 block 之前。

关于android - 如何在 Kotlin 中为 Any 类型声明扩展 val,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56748176/

相关文章:

android - 检查文件是否在android中存在

wpf - 依赖属性继承

c++ - 有没有我们*需要*在 C++ 中 protected 继承的例子?

android - Android | Kotlin回收 View 和自定义适配器仅创建一行

android - 无法在 androidTest 中使用 Kotlin 反引号方法名称 - 描述符异常错误

java - 媒体播放器不播放音频

java - Android setOnKeyListener导致ANR(Application Not Responding)提示

php - OOP如何管理存储在不同文件中的 'include'类

Android Studio 3.0支持Kotlin : Activity as Context

android - 可扩展 kotlin 中的 TextView