ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • [Kotlin] Reference and Reflection
    Kotlin 2019. 10. 22. 00:05

    필자는 Method Reference에 관하여 종종 많이 접할 수 있다. 

    안드로이드 스튜디오에서도 객체에 접근하기 위하여 

    객체::변수명, 객체::함수명 

    이런식으로 접근하는 걸 볼 수 있다. 

     

    오늘은 Reference가 무엇인지 살펴보자. 

     


    Property references

    class Person(val name: String, var age: Int)  {
    
        fun present() = "I'm $name, and I'm $age years old"
        fun greet(other: String) = "Hi, $other, I'm $name"
    }
    fun main() {
        val reference = Person::name  //methodReference
        println("reference $reference")
    
        val noReference = Person("Lisa",32)
        noreference.name
    }

    동일한 property에 관하여 접근해 보았다. 

    하나는 reference를 사용한 거고, 하나는 다르게 접근한 것이다. 

     

    위와 같 main()을 정하고 run()하면 아래와 같이 나타난다. 

    "Kotlin reflection is not available" 이라고 나와 있는데 속성에 대한 참조를 하는 것을 

    Property references라고 한다. 

    -
    KProperty

    코틀린 공식 문서에 가면 

    객체의 속성을 상속한 type이며, :: operator로 접근 할 수 있다고 명시되어 있다.

     

    객체의 속성을 읽거나 수정하고 싶다면 2가지 하위 인터페이스를 사용해야 한다. 

    • KProperty<R,V>                   //수정 X
    • KMutableProperty1<R,V>   // 수정 O

    모두 제네릭 인터페이스이고 R은 Receiver type(위 예제의 경우에는 Person), V는 속성이다. (Name)

     


    Function references

    Function references도 위의 Property references와 비슷하다. 

    Function reference는 KFunction<V>  인데, V가 function의 return type이다. 

    val g: KFunction<String> = Person::greet
    

    -

    KFucntion

    KFucntion은 parameter의 type이 몇개이냐에 따라서 subInterface의 이름이 정해진다. 

    KFunction1<A, V> -> 1개

    KFunction2<A, B, V>->  2개 

    KFunction3<A, B, C, V> ->3개 

    예를 들어 KFunction3<A, B, C, V>이 있다면 순서대로 A,B,C를 매개변수로 사용하고 V를 반환한다. 

     

    REF)

    * https://kotlinlang.org/docs/tutorials/kotlin-for-py/member-references-and-reflection.html

     

    Member references and reflection - Kotlin Programming Language

     

    kotlinlang.org

    위 예시는 참고 사이트의 예제를 사용하였습니다. 

    LIST

    'Kotlin' 카테고리의 다른 글

    [Kotlin] Data Class  (0) 2020.04.28
    [Kotlin]FoldRight && Fold  (0) 2019.12.27
    Kotlin in Action - Lamda  (0) 2019.09.24
    [Kotlin] Null Safety  (0) 2019.05.31
    [Kotlin]Basic Types  (0) 2018.09.21

    댓글

Designed by Tistory.