// 확장 함수 예제
// String 클래스에서 마지막 글자를 가져오는 확장 함수
fun main() {
val = str = "1234"
println(str.lastChar()) // 4
}
fun String.lastChar(): Char {
return this[this.length - 1]
}
this
를 통해 인스턴스에 접근 가능하다.private
또는 protected
멤버를 가져올 수 없다.
StringUtilsKt.lastChar(…)
fun String.lastChar: Char
get() = this[this.length - 1]
변수.함수이름(arument)
가 아닌 변수 함수이름 argument
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 // 중위 함수 호출
}
inline fun Int.add(other: Int): Int {
return this + other
}
fun main() {
3.add(4)
}
main
함수를 자바로 디컴파일하면 아래 코드로 된다.public static final void main() {
// ...
byte $this$add$iv = 3;
int other$iv = 4;
// ...
int var10000 = $this$add$iv + other$iv // 함수 호출이 아닌 복붙
}
fun createPerson(firstName: String, lastName: String): Person {
fun validateName(name: String) {
if (name.isEmpty()) {
throw IllegalArgumentException("...")
}
}
validateName(firstNamme)
validateName(lastName)
return Person(firstName, lastName)
}