IntArray vs Array <Int> in Kotlin

I'm not sure what the difference is between IntArrayand Array<Int>in Kotlin, and why I cannot use them interchangeably:

missmatch

I know what IntArraytranslates to int[]when targeting to JVM, but what does it mean Array<Int>to translate to?

In addition, you can also have String[]or YourObject[]. Why Kotlin has classes like {primitive}Arraywhen you can fit anything into an array, and not just primitives.

+19
source share
3 answers

Array<Int>is a whole Integer[]under the hood, and IntArray- int[]. It.

, Int Array<Int>, ( , Integer.valueOf()). IntArray , Java.


, . , 0 . IntArray , :

val arr = IntArray(10)
println(arr.joinToString()) // 0, 0, 0, 0, 0, 0, 0, 0, 0, 0

, Array<T> , : , T , . Number 0, T

Array<Int> , :

val arr = Array<Int>(10) { index -> 0 }  // full, verbose syntax
val arr = Array(10) { 0 }                // concise version

Array<Int?> , null , .

val arr = arrayOfNulls<Int>(10)
+32

( "" , Java).

Kotlin stdlib JVM, Java.

Array<T>, , Java- Java. IntArray.

: https://kotlinlang.org/docs/reference/basic-types.html#arrays

0

It is worth noting that using the spread ( *) operator in varargwill return IntArray. If you need Array<Int>, you can convert IntArrayusing .toTypedArray().

0
source

Source: https://habr.com/ru/post/1693804/


All Articles