How to initialize an array in Kotlin with values?

前端 未结 20 2129
谎友^
谎友^ 2020-12-22 21:03

In Java an array can be initialized such as:

int numbers[] = new int[] {10, 20, 30, 40, 50}

How does Kotlin\'s array initialization look li

20条回答
  •  醉酒成梦
    2020-12-22 21:24

    I'm wondering why nobody just gave the most simple of answers:

    val array: Array = [1, 2, 3]
    

    As per one of the comments to my original answer, I realized this only works when used in annotations arguments (which was really unexpected for me).

    Looks like Kotlin doesn't allow to create array literals outside annotations.

    For instance, look at this code using @Option from args4j library:

    
        @Option(
            name = "-h",
            aliases = ["--help", "-?"],
            usage = "Show this help"
        )
        var help: Boolean = false
    
    

    The option argument "aliases" is of type Array

提交回复
热议问题