본문 바로가기
코틀린/etc.

[Kotlin][Iteration Operation] repeat

by jinwo_o 2024. 8. 27.

주어진 함수 작업을 지정된 횟수만큼 실행합니다. 현재 반복의 0부터 시작하는 인덱스가 작업에 매개변수로 전달됩니다.

public inline fun repeat(times: Int, action: (Int) -> Unit) {
    contract { callsInPlace(action) }

    for (index in 0 until times) {
        action(index)
    }
}


repeat(3) { index -> print("Hello ")} // Hello Hello Hello

 

n 번 반복된 이 문자 시퀀스를 포함하는 문자열을 반환합니다.

public actual fun CharSequence.repeat(n: Int): String {
    require(n >= 0) { "Count 'n' must be non-negative, but was $n." }

    return when (n) {
        0 -> ""
        1 -> this.toString()
        else -> {
            when (length) {
                0 -> ""
                1 -> this[0].let { char -> String(CharArray(n) { char }) }
                else -> {
                    val sb = StringBuilder(n * length)
                    for (i in 1..n) {
                        sb.append(this)
                    }
                    sb.toString()
                }
            }
        }
    }
}


println("Word".repeat(4)) // WordWordWordWord
println("Word".repeat(0)) //

 

repeat - Kotlin Programming Language

 

kotlinlang.org

 

repeat - Kotlin Programming Language

 

kotlinlang.org