3

I have noticed that we can create classes in Kotlin without curly braces like below.

//Example classFile.kt
class Empty

class SecondEmpty

fun firstMethod() {

}

My question is, why we need such feature? in which situation we can use this?

In the above example, I have written a method called firstMethod() how can I call that from the other objects?

Willi Mentzel
  • 27,862
  • 20
  • 113
  • 121
Zumry Mohamed
  • 9,318
  • 5
  • 46
  • 51
  • Related: https://stackoverflow.com/questions/47588670/what-is-the-purpose-of-empty-class-in-kotlin – BakaWaii Dec 10 '17 at 04:06
  • Possible duplicate of [What is the purpose of empty class in Kotlin?](https://stackoverflow.com/questions/47588670/what-is-the-purpose-of-empty-class-in-kotlin) – Willi Mentzel Dec 11 '17 at 12:20

1 Answers1

2

Empty classes have been discussed in What is the purpose of empty class in Kotlin? already.

Regarding your firstMethod: in Kotlin, we have so called top-level functions. These can be defined in any file without an enclosing class. Another example for this is main which is defined top-level in most cases.

How to call top-level functions?

You can simply import the function into other files and call them. For instance, if firstMethod were defined in com/x/Example.kt (package com.x), you may import com.x.firstMethod in other Kotlin files and call that method.

For Java, it’s important to know, that top-level functions are compiled into a class as static members. As for the example above, you can call com.x.ExampleKt.firstMethod from Java.

s1m0nw1
  • 76,759
  • 17
  • 167
  • 196