Rooted In Develop

Kotlin - 함수 정의와 호출 본문

Back End/Kotlin

Kotlin - 함수 정의와 호출

RootedIn 2023. 4. 15. 23:16

컬렉션

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()
}

 

'Back End > Kotlin' 카테고리의 다른 글

Kotlin - 연산자 오버로딩  (0) 2023.05.27
Kotlin - 타입 시스템  (0) 2023.05.06
Kotlin - 클래스, 객체, 인터페이스  (0) 2023.05.01
Kotlin - 람다 프로그래밍  (0) 2023.05.01
Kotlin - 기초  (0) 2023.04.15
Comments