Just tried making the `main` function `private` in...
# getting-started
h
Just tried making the
main
function
private
in a kotlin file and it is still executable. How does JVM access the function if it is
private
and make it executable?
r
If you copy that into IntelliJ you can
Tools > Kotlin > Show Kotlin Bytecode
and then click the
Decompile
button at the top of the bytecode and see what Kotlin generated.
Main_java.java
👍 2
h
I see! Makes sense now 👍
r
As you can see, it generates a
public static void main
that calls your one, which is why yours being private doesn't matter.
k
Then why doesn't
private fun main(args: Array<String>)
work?
Where does it say in Kotlin documentation that an executable entry point must be
fun main(args: Array<String>)
,
fun main()
, or
private fun main()
but not
private fun main(args: Array<String>)
?
r
I don't know about the documentation. Using the decompiler, if you provide
args: Array<String>
as an argument then it doesn't generate a synthetic main method at all, so it can't make it public, so that's why it doesn't work.
👍 1
2
Copy code
private fun main(args: Array<String>) {
  println("hi")
}
becomes
Copy code
public final class MainKt {
   private static final void main(String[] args) {
      String var1 = "hi";
      System.out.println(var1);
   }
}
k
Thanks, that makes sense. Funnily enough, IntelliJ IDEA still thinks it's executable, and if you try to run it you get a JVM error.
2
j
Not sure if generating a public synthetic for a private
main
should be considered a feature or a bug to be honest 🤔
h
I think the reason it doesn't generate the synthetic method in this case is because of the method signature conflict it would result into?
👌 1
j
Yes, but it still doesn't explain why Kotlin finds it acceptable to generate a public synthetic for a
private fun main()
without arguments
r
I'd guess a bug.
j
Actually it does seem to be reported as a bug already: https://youtrack.jetbrains.com/issue/KT-31582
@Klitos Kyriacou actually the fact that it's runnable from IDEA is also reported as a related but separate bug: https://youtrack.jetbrains.com/issue/KTIJ-13974
k
Thanks. BTW it seems to do the right thing in Kotlin Native.