51

What alternative to an Inner static Class can I use in Kotlin Language, if it exists? If not, how can I solve this problem when I need to use a static class in Kotlin? See code example below:

 inner class GeoTask : AsyncTask<Util, Util, Unit>() {

    override fun doInBackground(vararg p0: Util?) {

        LocationUtil(this@DisplayMembers).startLocationUpdates()
    }
}

I've searched a lot, haven't found anything, Thank you very much in advance.

Mozahler
  • 4,958
  • 6
  • 36
  • 56
Osama Mohammed
  • 2,433
  • 13
  • 29
  • 61
  • What do you need an alternative _for_? What doesn't work? – Salem Mar 19 '18 at 12:55
  • in this code in my question, problem(memory Leak) occur because i using asynTask contain (context) of activity, android studio advice me to use (Inner Static class) – Osama Mohammed Mar 19 '18 at 13:00

3 Answers3

129

Just omit the inner in Kotlin.

Inner class (holding reference to outer object)

Java:

class A {
    class B {
    ...
    }
}

Kotlin:

class A {
    inner class B {
    ...
    }
}

Static inner class aka nested class (no reference to outer object)

Java:

class A {
    static class B {
    ...
    }
}

Kotlin:

class A {
    class B {
    ...
    }
}
Michael Butscher
  • 10,028
  • 4
  • 24
  • 25
5

You can also change the "class" to "object"

class OuterA {
  object InnerB {
  ... }
}

OR

object OuterA {
  object InnerB {
  ... }
}
Preeti Rani
  • 685
  • 7
  • 17
Clarence Chan
  • 51
  • 1
  • 2
0

In Android world, good practices are:

-Avoid non-static inner classes in activities;

-Use static inner classes with WeakReference so they can be GC-ed (Garbage Collected) when they are not used, as bellow example:

class MainActivity : AppCompatActivity() {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        MySingleton.init(this)
    }
}

object MySingleton {

    var weakContext: WeakReference<Context>? = null

    fun init(ctx: Context) {
        this.weakContext = WeakReference(ctx)
    }
}

When the MainActivity instance gets destroyed (onDestroy gets called), this weak reference to its context will get destroyed too; so no memory leaks occur. :]

GFPF
  • 959
  • 14
  • 19