My Java
code:
public class Common {
public static ModelPengguna currentModelPengguna;
}
My Java
code:
public class Common {
public static ModelPengguna currentModelPengguna;
}
public class Common {
companion object {
val currentModelPengguna: ModelPengguna = ModelPengguna()
}
}
or if the object is static and you want it as Singleton you can use
object Common {
val currentModelPengguna: ModelPengguna = ModelPengguna()
}
a static property in kotlin is introduced by the companion object
further reading:
https://kotlinlang.org/docs/reference/object-declarations.html#companion-objects
Java uses the same static
keyword for many features, like:
private static final String TAG = ...
While Kotlin separates these.
If we have a Java file, like:
public class MyClass {
private static final String TAG = "my-tag";
@NonNull
public static MyType myVariable = new MyType();
@Nullable
public static MyType myNullableVariable = null;
static {
Log.d(TAG, "Got this far!");
}
public void onSomething() {
onSomething(false);
}
public void onSomething(optionalArg: Boolean) {
// ...
}
}
Then the Kotlin version may look something like:
open class MyClass {
companion object {
private const val TAG = "my-tag"
@JvmStatic
var myVariable: MyType = MyType()
@JvmStatic
var myNullableVariable: MyType? = null
init {
Log.d(TAG, "Got this far!")
}
}
@JvmOverloads
open fun onSomething(optionalArg: Boolean = false) {
// ...
}
}
Where:
Kotlin's open class
is like Java's public class
.
The "@JvmStatic
" part allows Java to use Kotlin's myVariable
, as if it were Java's static
memeber.
The "@JvmOverloads
" part allows Java to call Kotlin's onSomething
without need to pass all parameters.
Note that "
: MyType
" part can be omitted, because both Kotlin and Android-studio IDE do auto-detect the type based on initializer (e.g. based on the "= MyType()
" part).Also,
@JvmStatic
and@JvmOverloads
do NOT need any import (as they're built-in features of Kotlin).
Static variables declare and initialize in to companion object for example:
public class MyClass {
companion object{
const val TAG: String = "my-tag"
const val myVariable: MyType = MyType()
var myNullableVariable: MyType? = null
}
}