kotlin

kotlin Array

slow333 2023. 2. 7. 18:52

Array class

It has get() and set() functions :

class Array<T> private constructor() {
    val size: Int
    operator fun get(index: Int): T
    operator fun set(index: Int, value: T): Unit

    operator fun iterator(): Iterator<T>
    // ...
}
 

array 생성

// Creates an Array<String> with values ["0", "1", "4", "9", "16"]
val asc = Array(5) { i -> (i * i).toString() }
asc.forEach { println(it) }

Primitive type arrays

기본형 array 지정 가능 : type 추론

val x: IntArray = intArrayOf(1, 2, 3)
x[0] = x[1] + x[2]
 
// Array of int of size 5 with values [0, 0, 0, 0, 0]
val arr = IntArray(5)

// Example of initializing the values in the array with a constant
// Array of int of size 5 with values [42, 42, 42, 42, 42]
val arr = IntArray(5) { 42 }

// Example of initializing the values in the array using a lambda
// Array of int of size 5 with values [0, 1, 2, 3, 4] (values initialized to their index value)
var arr = IntArray(5) { it * 1 }

 

'kotlin' 카테고리의 다른 글

kotlin 범위 지정 함수 : run/let, apply/also, with  (0) 2023.03.26
kotlin - lambda  (0) 2023.02.13
kotlin Cast - 형변환  (0) 2023.02.07
kotlin collection  (0) 2023.02.07
kotlin OOB- inheretance  (0) 2023.02.07