Please tell me, is there any difference (in terms of Java) in this examples:
object DefaultValues { val FILES_TO_DOWNLOAD = 100 }
and
class DefaultValues { companion object { val FILES_TO_DOWNLOAD = 100 } }
Without class or object wrapper:
const val DEFAULT_FILES_TO_DOWNLOAD = 100
and
val DEFAULT_FILES_TO_DOWNLOAD = 100
What is the true way to define?:
public static final int FILES_TO_DOWNLOAD = 100
Android Dependency Injection using Dagger with Kotlin In Java, once a method is declared as "static", it can be used in different classes without creating an object. With static methods, we don't have to create the same boilerplate code for each and every class.
Kotlin is a statically typed programming language for the JVM, Android and the browser, 100% interoperable with Java.
What is static data. Static data (aka Code, Lookup, List or Reference data), in the context of a relational database management system, is generally data that represents fixed data, that generally doesn't change, or if it does, changes infrequently, such as abbreviations for US states for example e.g. ME, MA, NC.
In Kotlin, you have the const keyword that's equal to the static keyword in Java. The const keyword is used to create a variable that's known to Kotlin before the compilation, so you don't need to create an instance of a class to use it.
You can use Kotlin bytecode viewer to find out what these options are compiled to.
With Kotlin 1.0.2 the compiled bytecode shows that
val
property in object
or companion object
is compiled into a private static final
field inside the class:
// access flags 0x1A private final static I FILES_TO_DOWNLOAD = 100
and a getter, which is called when referring to the property:
// access flags 0x1019 public final static synthetic access$getFILES_TO_DOWNLOAD$cp()I
From Java, the getter can be called as DefaultValues.INSTANCE.getFILES_TO_DOWNLOAD()
or DefaultValues.Companion.getFILES_TO_DOWNLOAD()
respectively.
Non-const
top level property is compiled to the same to (1) with only difference that the field and getter are placed inside FilenameKt
class now.
But top level const val
is compiled into a public static final
field:
// access flags 0x19 public final static I DEFAULT_FILES_TO_DOWNLOAD = 100
The same public static final field will be produced when a const val
is declared inside an object. Also, you can achieve the same resulting bytecode if you add @JvmField
annotation to the properties declared in (1).
Concluding that, you can define public static final
field using const
or @JvmField
either in an object
or at top level.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With