Basics

Extension Function은 클래스를 확장한다. 클래스 밖에서 정의 되지만 regular 멤버로 클래스 내부에서 호출할 수 있다.

fun String.getLast(number: Int) = this.get(this.length-1)
class Test{
 fun main(){
        val c: Char ="abc".getLast()
    }
}

Receiver

확장 함수가 호출 될 때는 this가 reveiver로서 호출된다. 또한 기본적으로 this의 멤버 변수나 함수를 호출하기 위해서 일일이 this를 정의할 필요가 없다.

fun String.getLast(number : Int)=get(length()-1)

Import

extension을 이용하기 위해선 import를 이용해서 명시해주어야 한다. 왜냐하면 extension function은 기본적으로 전체프로젝트에서 사용할 수 없도록 되어있기 때문이다.

fun String.lastChar()=get(length-1)

import com.example.util.lastChar
val c: Char="abc".lastChar()

Calling Extension Functions from Java code

자바에서 코틀린의 확장함수를 호출할때는 static형태로 호출된다. 이 또한 import를 통해서 static한 함수만을 호출 할 수 있다.

//StringExtension.kt
fun String.lastChar()=get(length-1)

//JavaClass.java
import static StringExtensionKt.lastChar;
char c=lastChar("abc");
//or
char c=StringExtensionKt.lastChar("abc");

위에서 보듯 자바에서 확장함수를 호출할때는 첫 번째 파라미터로 리시버를 입력한다. 확장함수가 추가적인 파라미터가 필요하다면 자바에서는 두 번째 파라미터부터 입력하면 된다.

//StringExtension.kt
fun String.getChar(pos : Int)=get(pos)

//JavaClass.java
import static StringExtensionKt.getChar;
char c=getChar("abc",2);

Accessing private members

자바에서는 다른 클래스의 static 함수에서 private member를 호출할 수 없다.

코틀린의 확장함수는 분리된 보조 클래스에서 정의된 static 함수이다.

따라서 확장함수에서는 private member를 호출 할 수 없다.

Reference

Examples from the Standard Library - Starting up with Kotlin | Coursera

+ Recent posts