Home > OS >  can I create top level instance in kotlin?
can I create top level instance in kotlin?

Time:07-22

If I have app.kt file in kotlin, can I create instance like appKt()? Thanks. Kotlin has top level function. For example I can write in app.kt:

val a = 123
fun abc() {}
appKt.abc()

my question is if I can create appKt instance and call instance method

CodePudding user response:

Only classes can be instanced.

Instead of loose function fun abc() {}, this should be the method of a class:

class appKt() {
    // private var a: Integer = 123
    fun abc() {}
}

CodePudding user response:

No, you can't put arbitrary code at the top level.

You can put only definitions of classes (just as in Java), objects, functions, and properties.

It wouldn't make much sense to put loose code there, anyway: when would it run?

It's not clear what you're trying to achieve with this. If you want some code that gets run when your program starts up, then you could put it into a top-level function — but you'd then have to call that function (e.g. from your main() method). Or you could put it in the init block of the companion object to a class that you know will be loaded. Or if you're using a framework such as Android or Spring, then that will probably provide ways to specify code to be run at start-up.

  • Related