kotlin中companion object {}
时间: 2024-03-20 09:39:11 浏览: 29
在 Kotlin 中,`companion object` 是一种特殊的对象,可以让我们在类中定义一些静态成员。与 Java 不同,Kotlin 中没有 static 关键字,而是使用 `companion object` 来实现类似的功能。`companion object` 中的成员可以直接使用类名访问,就像 Java 中的静态成员一样。
`companion object` 中定义的成员包括属性、方法和嵌套类。可以使用 `@JvmStatic` 注解将 `companion object` 中的成员标记为 Java 中的静态成员,从而可以在 Java 代码中直接使用类名访问。
下面是一个使用 `companion object` 的例子:
```kotlin
class MyClass {
companion object {
const val MAX_COUNT = 10
fun printMessage() {
println("Hello from companion object!")
}
class MyNestedClass {
// ...
}
}
}
// 访问 companion object 中的属性和方法
MyClass.MAX_COUNT
MyClass.printMessage()
// 访问 companion object 中的嵌套类
val nested = MyClass.MyNestedClass()
```
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)