Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What are the differences between Java and Kotlin inner/local/anonymous classes?

Tags:

java

kotlin

What are the name equivalents and main differences between Java and Kotlin nested/inner/local classes?

like image 580
JuanMoreno Avatar asked Mar 06 '23 15:03

JuanMoreno


1 Answers

These are the name equivalents:

| Kotlin            | Java                                      |
|-------------------|-------------------------------------------|
| Inner Classes     | Non-Static Nested Classes / Inner Classes |
| Nested Classes    | Static Nested Classes                     |
| Local Classes     | Local Classes                             |
| Anonymous Objects | Anonymous Classes                         |

This is a quick overview of differences:

  • In both cases, we can group multiple classes in the same file. However, in Kotlin we can have multiple top-level classes in the same .kt file, in Java we can have many classes per compilation unit but only one can be public.
  • Kotlin anonymous objects have support to implement multiple interfaces.
  • Java anonymous classes are limited to implement only one abstract class or interface.
  • In Kotlin we can mutate a local variable from a closure; because of that the Java concept of effectively final doesn't apply to Kotlin.
  • In Kotlin inner classes to reference the instance of the outer class, we need to use the qualifier this expression.

    Some examples can be found over on this tutorial.

like image 125
JuanMoreno Avatar answered Mar 14 '23 03:03

JuanMoreno