1

In my (2.0.0.M6) kotlin-spring boot app, everything works fine when I do

fun main(args: Array<String>) {
   runApplication<MyApplication>(*args)
}

but the mainClass can not be found and IDEA does not allow running the app when I do

fun main(args: Array<String>) = runApplication<RankedApplication>(*args)

this is not critical at all, but I wonder: why?

Jan Galinski
  • 11,768
  • 8
  • 54
  • 77

2 Answers2

5

runApplication does not return Unit.

The signature and return type of main must be exactly:

fun main(Array<String>): Unit

runApplication, though, returns a ConfigurableApplicationContext.

Your "main" method is equivalent to:

fun main(args: Array<String>): ConfigurableApplicationContext {
    return runApplication<MyApplication>(*args)
}

since the return type is deduced from the expression - and you can see this is not a valid entry point.

Your first method works because

fun main(args: Array<String>) {
    runApplication<MyApplication>(*args)
}

is the same as

fun main(args: Array<String>): Unit {
    runApplication<MyApplication>(*args)
    return Unit
}

since Unit (a singleton object) is the default return type when none is specified, and is implicitly returned at the end of a method declared to return Unit.

This is also why return without an argument is valid - it just returns Unit.


If you wanted to, you could make a method to convert things to Unit though this is probably overkill.

inline fun Unit(lambda: () -> Any?) {
    lambda()
}

...

fun main(args: Array<String>) = Unit { runApplication<MyApplication>(*args) }

It's the same in Java, which is likely where this requirement comes from - the main method's signature must be public static void main(String[]).

Salem
  • 13,516
  • 4
  • 51
  • 70
2
fun main(args: Array<String>) {
   runApplication<MyApplication>(*args)
}

main returns Unit here implicitely which is correct.

Here

fun main(args: Array<String>) = runApplication<RankedApplication>(*args)

the return type is inferred from the given expression to something other than Unit (because runApplication returns something) which does not work because the main function has to return Unit.

Willi Mentzel
  • 27,862
  • 20
  • 113
  • 121