Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Change main to accept Array<out String> #196

Closed
JakeWharton opened this issue Jun 19, 2020 · 2 comments · Fixed by #197
Closed

Change main to accept Array<out String> #196

JakeWharton opened this issue Jun 19, 2020 · 2 comments · Fixed by #197

Comments

@JakeWharton
Copy link

Since it never mutates the array and simply creates a list, main(args: Array<String>) should ideally be main(args: Array<out String>). This will improve the compatibility with the three ways you can define the parameter for a normal main method.

Here's an illustrative example:

fun testMain(vararg varargString: String) {
  val arrayString: Array<String> = emptyArray()
  val arrayOutString: Array<out String> = emptyArray()
  
  exampleNoOut(varargString)
  exampleNoOut(arrayString)
  exampleNoOut(arrayOutString)
  
  exampleOut(varargString)
  exampleOut(arrayString)
  exampleOut(arrayOutString)
}

fun exampleNoOut(args: Array<String>) = Unit
fun exampleOut(args: Array<out String>) = Unit

And what it looks like in the IDE:
Screen Shot 2020-06-19 at 4 11 59 PM

This is a binary-compatible change since variance is a concept solely implemented in the compiler (like generics in general). It also should be a source-compatible change as you can see above, but also because Array<out String> is more permissive than Array<String> in what it accepts.

ajalt added a commit that referenced this issue Jun 20, 2020
ajalt added a commit that referenced this issue Jun 20, 2020
@ajalt
Copy link
Owner

ajalt commented Jun 20, 2020

TIL that you can declare main as vararg. The bytecode's the same, so it makes sense, but I've never seen it mentioned in any docs.

@JakeWharton
Copy link
Author

Same is true of Java!

public static void main(String... args) {
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging a pull request may close this issue.

2 participants