简体   繁体   中英

Static Inner Class in Kotlin

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.

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

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

class OuterA {
  object InnerB {
  ... }
}

OR

object OuterA {
  object InnerB {
  ... }
}

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. :]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM