IT/Kotlin
Kotlin - function, Lambda, Reflection
은고고
2021. 12. 30. 15:23
반응형
:: (Reflection)
참조로 이해하면 되겠다. 즉 직접적인 함수 호출, 속성 접근이 아니다.
Reflection | Kotlin
kotlinlang.org
아래 코드는
function, extention, lambda 선언과 Reflection 사용 예이다.
// normal function
fun normalfunctionPrintSquare(a: Int): Unit {
println(a * 2)
}
// single-expression function
fun singleexpressionfunctionPrintSquare(a: Int): Unit = println(a * 2)
// generic function
fun <T: Int> genericfunctionPrintSquare(a: T): Unit {
println(a * 2)
}
// extention function
fun Int.printSquare(): Unit {
println(this * 2)
}
// extention property
val Int.Square: Int
get() = this * 2
// lambda
val lambdaPrintSquare = { t: Int -> println( t * 2 ) }
// My class
class MyInt() {
var square: Int = 5
get() = field * 2
fun printSquare(a: Int): Unit {
println(a * 2)
}
}
/* client code */
fun myfunc(printSq: (Int) -> Unit) {
printSq(5)
}
fun main() {
// myfunc(::lambdaPrintSquare) // compile error
myfunc(lambdaPrintSquare)
//myfunc(normalfunctionPrintSquare) // compile error
myfunc(::normalfunctionPrintSquare)
myfunc(::singleexpressionfunctionPrintSquare)
myfunc(::genericfunctionPrintSquare)
// extention property reference
println(Int::Square.get(5))
// extention function call
5.printSquare()
// class method
val intSq: (MyInt, Int) -> Unit = MyInt::printSquare
intSq.invoke(MyInt(), 5)
// class property
val s = MyInt::square
println(s.get(MyInt()))
}
반응형