https://kotlinlang.org logo
Title
h

harry.singh

02/21/2022, 5:22 PM
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

Rob Elliot

02/21/2022, 5:36 PM
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.
h

harry.singh

02/21/2022, 5:38 PM
I see! Makes sense now 👍
r

Rob Elliot

02/21/2022, 5:38 PM
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

Klitos Kyriacou

02/21/2022, 5:38 PM
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

Rob Elliot

02/21/2022, 5:46 PM
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
private fun main(args: Array<String>) {
  println("hi")
}
becomes
public final class MainKt {
   private static final void main(String[] args) {
      String var1 = "hi";
      System.out.println(var1);
   }
}
k

Klitos Kyriacou

02/21/2022, 5:51 PM
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

Joffrey

02/21/2022, 5:53 PM
Not sure if generating a public synthetic for a private
main
should be considered a feature or a bug to be honest 🤔
h

harry.singh

02/21/2022, 5:53 PM
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?
:yes: 1
j

Joffrey

02/21/2022, 5:54 PM
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

Rob Elliot

02/21/2022, 5:55 PM
I'd guess a bug.
j

Joffrey

02/21/2022, 5:57 PM
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

Klitos Kyriacou

02/21/2022, 6:01 PM
Thanks. BTW it seems to do the right thing in Kotlin Native.