반응형
buildList는 Kotlin의 표준 라이브러리에서 제공하는 함수인데요.
오늘은 이것에 대해 정리하겠습니다.
1. BuildList
buildList 함수를 사용하면,
MutableList에 아이템을 추가하거나 제거하는 등의 변화를 준 후,
변경 불가능한(immutable) List로 리턴해 줍니다.
예제를 보면서 이해해 보겠습니다.
buildList블록안에서,
x라는 리스트의 앞과 뒤에,
아이템을 추가하였습니다.
val x = listOf('김', '이')
val y = buildList() {
add('박')
addAll(x)
add('마')
}
println(y) // ['박', '김', '이', '마']
2. 실제 코드
실제로 사용하는 코드를 볼까요?
예전코드와,
buildList를 사용하는 코드를 비교해보면 좋을 것 같네요.
예전에는 아래와 같이 코드를 작성했습니다.
여러개의 헤더를 가지는 RecyclerView등을 사용할 때,
저렇게 할 수 있겠지요.
val result = mutableListOf<NoteFeedListItem>()
if (favoriteNotes.isNotEmpty()) {
result.add(NoteFeedListItem.FavoriteHeader)
favoriteNotes.forEach { result.add(NoteFeedListItem.NoteItem(it)) }
}
return result.toList()
이제 buildList를 사용하는 코드를 볼까요?
리턴하지도 않을 변수를 만들어서 사용할 필요가 없어지고요.
리턴할 때는 immutable하게 리턴해 줍니다.
return buildList {
if (favoriteNotes.isNotEmpty()) {
add(NoteFeedListItem.FavoriteHeader)
favoriteNotes.forEach { add(NoteFeedListItem.NoteItem(it)) }
}
}
이상으로 Kotlin의 buildList에 대해 알아보았습니다.
728x90
'Android 개발 > Kotlin' 카테고리의 다른 글
Kotlin Lateinit var와 By Lazy 차이 이해하기 (0) | 2025.02.17 |
---|---|
Kotlin Smart Cast(스마트캐스트) 총정리 (0) | 2025.01.22 |
ifEmpty 와 orEmpty 에 대해서 알아보자 # Kotlin (0) | 2023.05.30 |
CoerceIn, coerceAtMost, coerceAtLeast 범위지정 함수에 대한 정리 # Kotlin (0) | 2023.05.26 |
MapNotNull 과 MapNotNullTo 에 대한 정리 # null 제거 (0) | 2023.05.24 |
List 아이템 부분추출 함수 정리 # take, takeWhile, takeLast, drop, slice, first and last (0) | 2023.05.15 |
compareBy 와 min 그리고 sortedWith 사용방법에 대한 정리 (0) | 2023.05.10 |
any , contains, none , all, containsAll 에 대한 정리 # Kotlin list 존재여부 확인 (1) | 2023.05.06 |
Destructuring declaration 에 대해 알아보자 # 구조분해 선언 Kotlin (0) | 2023.05.01 |
Kotlin Escape 에 대한 정리 # RawString Escaped String Literal (0) | 2023.04.30 |
댓글