Kotlin 中 Java 静态最终字段的等价物是什么?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/40352879/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-11 22:37:54  来源:igfitidea点击:

What is the equivalent of Java static final fields in Kotlin?

javakotlin

提问by pdeva

In Java, to declare a constant, you do something like:

在 Java 中,要声明一个常量,您可以执行以下操作:

class Hello  {
 public static final int MAX_LEN = 20;
}

What is the equivalent in Kotlin?

Kotlin 中的等价物是什么?

采纳答案by Ruslan

According Kotlin documentationthis is equivalent:

根据 Kotlin文档,这是等效的:

class Hello {
    companion object {
        const val MAX_LEN = 20
    }
}

Usage:

用法:

fun main(srgs: Array<String>) {
    println(Hello.MAX_LEN)
}

Also this is static final property (field with getter):

这也是静态最终属性(带有 getter 的字段):

class Hello {
    companion object {
        @JvmStatic val MAX_LEN = 20
    }
}

And finally this is static final field:

最后这是静态最终字段:

class Hello {
    companion object {
        @JvmField val MAX_LEN = 20
    }
}

回答by Gary LO

if you have an implementation in Hello, use companion objectinside a class

如果您有一个实现Hello,请companion object在类中使用

class Hello {
  companion object {
    val MAX_LEN = 1 + 1
  }

}

if Hellois a pure singleton object

ifHello是一个纯单例对象

object Hello {
  val MAX_LEN = 1 + 1
}

if the properties are compile-time constants, add a constkeyword

如果属性是编译时常量,则添加一个const关键字

object Hello {
  const val MAX_LEN = 20
}

if you want to use it in Java, add @JvmStaticannotation

如果你想在Java中使用它,添加@JvmStatic注释

object Hello {
  @JvmStatic val MAX_LEN = 20
}

回答by Simon Ludwig

For me

为了我

object Hello {
   const val MAX_LEN = 20
}

was to much boilerplate. I simple put the static final fields above my class like this

太多样板了。我简单地将静态最终字段放在我的班级之上

val MIN_LENGTH = 10

class MyService{
}