컬렉션
val rank = listOf("1st", "2nd", "3rd")
val ints = setOf(1, 2, 3)
함수 정의
fun <T> joinToString(
collection: Colletion<T>,
separator: String = ",",
prefix: String = "(",
postfix: String = ")"
) : String {
val result = StringBuilder(prefix)
for ((index, element) in collection.withIndex()) {
if (index > 0) result.append(separator)
result.append(element)
}
result.append(postfix)
return result.toStrinig()
}
joinToString(collection, ",", "(", ")")
joinToString(collection)
joinToString(collection, separator = "/", prefix = "[", postfix = "]")
확장 함수
fun String.lastChar(): Char = get(length - 1)
확장 프로퍼티
val String.lastChar: Char
get() = get(length - 1)
set(value: Char) {
this.setCharAt(length - 1, value)
}
"Kotlin".lastChar = 'x'
가변 인자 함수
fun listOf<T>(vararg values: T): List<T> { }
중위 호출
1.to("one") // 일반적인 방식
1 to "one" // 중위 호출 방식
구조 분해 선언
val (number,name) = 1 to "one"
로컬 함수
// 로컬 함수로 추가하기
fun saveUser(user: User) {
fun validate(value: String) {
if (value.isEmpty()) {
throw IllegalArgumentException("${user.id}")
}
}
validate(user.name)
validate(user.address)
}
// 확장 함수로 추출하기
fun User.validateBeforeSave() {
fun validate(value: String) {
if (value.isEmpty()) {
throw IllegalArgumentException("${user.id}")
}
}
validate(user.name)
validate(user.address)
}
fun saveUser(user: User) {
user.validateBeforeSave()
}