Search code examples
kotlinjunit

Kotlin - How to be able to run and test function?


I am creating demo code in Kotlin. I am trying so students should be able:

  • run function itself
  • run test

For example: If function is created in .kt file, outside of class:

fun main(){
    print("Hello world!")
}
  • it can be run
  • but I could not find the way to call it from the test

If the function is inside the class:

class Hello {
    fun main(){
        print("Hello world!")
    }
}
  • the function can be called from the test
  • but can not be run - the green "Run" button is not visible.

Question: How to make such a function can be run manually and by test at the same time?


Solution

  • 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.

    See more documentation here