Kotlin에서 repeat와 takeLast는 데이터 처리와 반복 작업에서 자주 사용되는 함수입니다.
repeat 함수는 특정 작업을 지정된 횟수만큼 반복 실행할 때 사용됩니다. 반복 동작을 간결하게 표현할 수 있어 코드의 가독성을 높입니다.
repeat(2) {
println("Hello, Kotlin!")
}
// Hello, Kotlin! 출력
// Hello, Kotlin! 출력
repeat 함수는 반복 블록 내부에서 현재 반복의 index를 제공합니다.
repeat(3) { index ->
println("Index: $index")
}
// Index: 0 출력
// Index: 1 출력
// Index: 2 출력
list에 데이터를 반복적으로 추가하거나 특정 문자열을 반복 생성할 때 repeat 함수를 사용할 수 있습니다.
val stars = StringBuilder()
repeat(5) {
stars.append("*")
}
println(stars.toString()) // ***** 출력
takeLast 함수는 list나 string의 끝에서 지정한 개수만큼 요소를 가져옵니다. 만약 요청한 개수가 collection의 크기보다 크다면, 전체 요소를 반환합니다.
val numbers = listOf(1, 2, 3, 4, 5)
println(numbers.takeLast(2)) // [4, 5] 출력
val text = "Hello, Kotlin!"
println(text.takeLast(7)) // "Kotlin!" 출력
val numbers = listOf(1, 2, 3)
println(numbers.takeLast(5)) // [1, 2, 3] 출력