Home > Enterprise >  What is the equivalent of Java static class in Kotlin?
What is the equivalent of Java static class in Kotlin?

Time:09-27

There is no static keyword in kotlin.

what is the equivalent of java static class in kotlin?

CodePudding user response:

If you just declare a class inside another class, the inner class can be instantiated without an instance of the outer class, similar to Java static classes:

class Outer {
    class Inner
}

// can do "Outer.Inner()" directly without an instance of Outer

You don't need any modifiers.

If you want something similar to Java's non-static classes, you would need to add the word inner:

class Outer {
    inner class Inner
}

// need an instance of Outer to create an instance of Outer.Inner

To summarise:

needs an outer instance does not need an outer instance
Java no modifier static
Kotlin inner no modifier

CodePudding user response:

Kotlin does not define entire static class as “static classes”. Instead, we use what is called an object declaration.
Even if you wanted a single static function/method in a non-static class, you need to create what is called a companion object within your class.
as an Example:

class Example {
   companion object Factory {
    fun create(): Example = Example()
   }
}  

as you see it implements factory patterns which allows for an object to create the instance of itself in a lazy fashion, using static methods
The name of companion is optional so can say it in this way too:

class Example {
  companion object {
     fun create(): Example = Example()
  }
}  

Now you can simply say:

Example.create()

also you can use object declarations at the package level the same as companion
see this:

object Example{
fun create(): Example= Example() 
} 

then you can use it like this if the package is imported:

Example.create()

also see this -> Docs

  • Related