简体   繁体   English

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

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

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 中的等价物是什么?

According Kotlin documentation this 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
    }
}

if you have an implementation in Hello , use companion object inside a class如果您在Hello中有实现,请在类中使用companion object

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

}

if Hello is a pure singleton object如果Hello是纯单例对象

object Hello {
  val MAX_LEN = 1 + 1
}

if the properties are compile-time constants, add a const keyword如果属性是编译时常量,则添加const关键字

object Hello {
  const val MAX_LEN = 20
}

if you want to use it in Java, add @JvmStatic annotation如果要在 Java 中使用,请添加@JvmStatic注解

object Hello {
  @JvmStatic val MAX_LEN = 20
}

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我像这样简单地将静态最终字段放在我的类上方

private val MIN_LENGTH = 10 // <-- The `private` scopes this variable to this file. Any class in the file has access to it.

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM