-1

I have this Java code

 public class CrimeLab {
 private static CrimeLab sCrimeLab;
 public static CrimeLab get(Context context) {
     if (sCrimeLab == null) {
     sCrimeLab = new CrimeLab(context);
  }
       return sCrimeLab;
  }
    private CrimeLab(Context context) {
   }
}

I am writing this Kotlin Code

object CrimeLab {

    }

Not sure how to pass "Context" while the object is created for CrimeLab.

Sourav
  • 139
  • 1
  • 1
  • 9

1 Answers1

0

You can't pass arguments as constructor params to object type in kotlin

Right, in kotlin object is singleton but, object has no constructor, but has init{...} method which calls when object is just created.

Option: Make optional function like: fun get(context: Context):CrimeLab { ... return this }

best solution is pass context to function which need it,

fun initialize(context: Context) {...} ...

and in your activity or wherever call like

CrimeLab.initialize(this)

NOTE: do not set context of view instance as a field in object type (singleton), avoid memory leaks.

Narek Hayrapetyan
  • 1,731
  • 15
  • 27