Zumry Mohamed
Zumry Mohamed

Reputation: 9558

Kotlin classes without curly braces

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?

Upvotes: 3

Views: 3157

Answers (1)

s1m0nw1
s1m0nw1

Reputation: 82087

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.

Upvotes: 2

Related Questions