I am creating demo code in Kotlin. I am trying so students should be able:
For example: If function is created in .kt file, outside of class:
fun main(){
print("Hello world!")
}
If the function is inside the class:
class Hello {
fun main(){
print("Hello world!")
}
}
Question: How to make such a function can be run manually and by test at the same time?
I'll assume you are writing your tests in Java, because if it's in Kotlin, calling main
is trivial: main()
, provided that you have imported the package/in the same package.
Kotlin global functions are compiled into static methods of a class with a name similar to the Kotlin file in which the function is declared, suffixed with Kt
For example, if the file is called "app.kt", the class name would be AppKt
. So if you declared main
in app.kt
, you would call:
AppKt.main();
in Java
You can change this name by annotating the Kotlin file with @JvmName
:
@file:JvmName("MyOwnName")
Then you can call:
MyOwnName.main();
in Java.