10

My Java code:

public class Common {
    public static ModelPengguna currentModelPengguna;
}
Top-Master
  • 7,611
  • 5
  • 39
  • 71
Kang sigit
  • 109
  • 1
  • 3
  • 3
    If you describe your objective we can recommend more idiomatic Kotlin. – charles-allen Jun 09 '19 at 12:22
  • 2
    Possible duplicate of [Kotlin static methods and variables](https://stackoverflow.com/questions/43857824/kotlin-static-methods-and-variables) – N J Jun 09 '19 at 13:43

3 Answers3

15
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

N J
  • 27,217
  • 13
  • 76
  • 96
Naor Tedgi
  • 5,204
  • 3
  • 21
  • 48
1

Java uses the same static keyword for many features, like:

  • Global variable/ property.
  • Constant, like: private static final String TAG = ...
  • Class's on-load initializer - which Java names Static-block.

While Kotlin separates these.

Example

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).

Top-Master
  • 7,611
  • 5
  • 39
  • 71
0

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
    }
}