Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 509
Osama Mohammed Avatar asked Mar 19 '18 12:03

Osama Mohammed


People also ask

Is there static class in Kotlin?

Android Dependency Injection using Dagger with Kotlin In Java, once a method is declared as "static", it can be used in different classes without creating an object. With static methods, we don't have to create the same boilerplate code for each and every class.

What is a static inner class?

A static inner class is a nested class which is a static member of the outer class. It can be accessed without instantiating the outer class, using other static members. Just like static members, a static nested class does not have access to the instance variables and methods of the outer class.

Can we use static in inner class?

As with instance methods and variables, an inner class is associated with an instance of its enclosing class and has direct access to that object's methods and fields. Also, because an inner class is associated with an instance, it cannot define any static members itself.


2 Answers

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 {     ...     } } 
like image 66
Michael Butscher Avatar answered Oct 05 '22 22:10

Michael Butscher


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

class OuterA {   object InnerB {   ... } } 

OR

object OuterA {   object InnerB {   ... } } 
like image 32
Clarence Chan Avatar answered Oct 06 '22 00:10

Clarence Chan