Static Inner Class in Kotlin
Asked Answered
R

3

56

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.

Rapier answered 19/3, 2018 at 12:51 Comment(2)
What do you need an alternative for? What doesn't work?Lumen
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)Rapier
I
136

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 {
    ...
    }
}
Infra answered 19/3, 2018 at 14:50 Comment(0)
K
5

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

class OuterA {
  object InnerB {
  ... }
}

OR

object OuterA {
  object InnerB {
  ... }
}
Kwangtung answered 3/4, 2020 at 10:29 Comment(2)
What's the difference in this case?Darwin
It might help: kotlinlang.org/docs/…Pm
P
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. :]

Pm answered 16/11, 2022 at 22:14 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.