我们为什么要使用“伴侣对象"?作为Kotlin中Java静态字段的替代品? [英] Why do we use "companion object" as a kind of replacement for Java static fields in Kotlin?

查看:117
本文介绍了我们为什么要使用“伴侣对象"?作为Kotlin中Java静态字段的替代品?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

伴侣对象"的预期含义是什么?到目前为止,我一直在用它来代替Java的static.

What is the intended meaning of "companion object"? So far I have been using it just to replace Java's static when I need it.

我很困惑:

  • 为什么叫同伴"?
  • 这是否意味着要创建多个 static 属性,我必须将其分组到companion object块中?
  • 要立即创建一个作用于某个类的单例实例,我经常写
  • Why is it called "companion"?
  • Does it mean that to create multiple static properties, I have to group it together inside companion object block?
  • To instantly create a singleton instance that is scoped to a class, I often write

:

companion object {
    val singleton by lazy { ... }
}

似乎是一种惯用的方式.有什么更好的方法?

which seems like an unidiomatic way of doing it. What's the better way?

推荐答案

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆