Search code examples
javakotlinsyntaxnew-operator

Kotlin array literal syntax like java


Just a simple question

when we will get array literal syntax in kotlin like java

var array = arrayOf<Int>(1,2,3,4,5) // current syntax
var array = {1,2,3,4,5} // new syntax

If any of you have information on the current status of this feature or if it has already been implemented in a newer version that I might have missed, I would greatly appreciate your insights. Additionally, any tips or workarounds for achieving a more compact syntax while working with arrays in Kotlin would be welcome.


Solution

  • That specific syntax with curly brackets I think will never happen because it's too close to the Kotlin syntax for lambdas. For example, it would break existing code like:

    val x = { 1 } // type of x is inferred to be () -> Int
    

    However, they are at least considering it with square brackets. That can be followed here in the official YouTrack issues list. This issue was opened by the lead Kotlin designer, so it's not just wishful thinking from a random user. Unfortunately, there is no planned implementation date yet.

    A couple of possibilities for shortening it:

    The <Int> in your code is redundant and can be dropped, because the type can be inferred by the compiler when the array is not empty.

    You can use a function alias like

    import kotlin.arrayOf as a
    

    so you could write code like

    val x = a(1, 2, 3, 4)
    

    in files where you create a lot of literal arrays.