TIL

Lec 16. 코틀린에서 다양한 함수를 다루는 방법

1. 확장함수

// 확장 함수 예제
// String 클래스에서 마지막 글자를 가져오는 확장 함수

fun main() {
  val = str = "1234"
  println(str.lastChar()) // 4
}

fun String.lastChar(): Char {
  return this[this.length - 1]
}
fun String.lastChar: Char
    get() = this[this.length - 1]

2. infix 함수

fun Int.add(other: Int): Int {
  return this + other
}

infix fun Int.add2(other: Int): Int {
  return this + other
}

fun main() {
  3.add(4) // 함수 호출
  
  3 add 4 // 중위 함수 호출
}

3. inline 함수

inline fun Int.add(other: Int): Int {
  return this + other
}

fun main() {
  3.add(4)
}
public static final void main() {
  // ...
  byte $this$add$iv = 3;
  int other$iv = 4;
  // ...
  int var10000 = $this$add$iv + other$iv // 함수 호출이 아닌 복붙
}

4. 지역 함수

fun createPerson(firstName: String, lastName: String): Person {
  fun validateName(name: String) {
    if (name.isEmpty()) {
      throw IllegalArgumentException("...")
    }
  }
  validateName(firstNamme)
  validateName(lastName)
  return Person(firstName, lastName)
}