There are multiple ways to declare and initialise Arrays in Kotlin. An Array<Short>
can be initialised in the following ways -
val shortArr1 = shortArrayOf(1,2,3,4,5)
//or
val shortArr2: Array<Short> = arrayOf(1,2,3,4,5)
But, what if the values are complicated and I want to initialise the values using a lambda function, such as -
val shortArr3 = Array<Short>(10){n -> n*2}
This statement throws -
error: type mismatch: inferred type is Int but Short was expected
The above expression would have worked for an Array<Int>
since n
by default is of type Int. Hence, what is the correct way to initialise an Array using lambda function, in Kotlin?
To initialize an Array using a lambda function in Kotlin, you can explicitly specify the type of the lambda parameter as Short. Here's the correct way to initialize the array:
val shortArr3 = Array(10) { n: Int -> (n * 2).toShort() }
In this example, the lambda function takes an Int parameter n and multiplies it by 2. The result is then converted to Short using the toShort() function.
By explicitly specifying the type of the lambda parameter as n: Int, you ensure that the multiplication operation is performed with Int values and then converted to Short explicitly. This resolves the type mismatch error.