In Kotlin, a nested class is a class defined inside another class. The nested class can be accessed using the name of the enclosing class as a qualifier. This allows for better organization of the code and can make the code more readable and easier to maintain.
There are two types of nested classes in Kotlin:
1) Inner class: an inner class is a nested class that has access to the members of the enclosing class. To define an inner class, use the keyword "inner" before the class declaration. Inner classes are useful when you need to access the properties and methods of the enclosing class from the nested class.
For example, suppose you have a class called "Outer" and you want to define an inner class called "Inner" that can access a property of "Outer". Here is an example:
class Outer {
private val property: Int = 1
inner class Inner {
fun accessProperty() {
println("Property value is $property")
}
}
}
class Outer {
private val property: Int = 1
class Nested {
fun doSomething() {
println("Doing something")
}
}
}