tonykang22 / study

0 stars 0 forks source link

[Kotlin & Spring] 05. 확장 함수 #114

Open tonykang22 opened 1 year ago

tonykang22 commented 1 year ago

05. 확장 함수

확장 함수란


MyStringExtensions.kt

fun String.first(): Char {
    return this[0]
}

fun String.addFirst(char: Char): String {
    return char + this.substring(0)
}

fun main() {
    println("ABCD".first())   // 출력 : A

    println("ABCD".addFirst('Z'))   // 출력 : ZABCD
}




자바로 변환된 확장 함수

import org.jetbrains.annotations.NotNull;

public final class Java_MyStringExtensionsKt {

  public static final char first(@NotNull String $this) {
    return $this.charAt(0);
   } 
}


멤버와 중복될 경우

class MyExample {

    fun printMessage() = println("클래스 출력")
}

fun MyExample.printMessage() = println("클래스 출력")

fun main() {
    MyExample().printMessage()
    // 클래스 출력
}


class MyExample {

    fun printMessage() = println("클래스 출력") 
}

fun MyExample.printMessage(message: String) = println(message)

fun main() {
    MyExample().printMessage("확장 출력")
    // 확장 출력
}



널 가능성이 있는 클래스에 대한 확장

class MyExample {
  /* ... */
}

fun MyExample?.printNullOrNotNull() {
    if (this == null) println("널인 경우에만 출력")
    else println("널이 아닌 경우에만 출력")
}

fun main() {
    var myExample: MyExample? = null
    myExample.printNullOrNotNull()
    // 널인 경우에만 출력

    myExample = MyExample()
    myExample.printNullOrNotNull()
    // 널이 아닌 경우에만 출력
}