시배's Android

Kotlin vs Java | by 델리게이트는 자바로 어떻게 구현이 될까? 본문

Kotlin/Kotlin vs Java

Kotlin vs Java | by 델리게이트는 자바로 어떻게 구현이 될까?

si8ae 2024. 2. 22. 22:59
import kotlin.reflect.KProperty

fun main(){
   val test : Int by LoggingProperty(100)
   println(test)
}

class LoggingProperty<T> (var value : T) {
   operator fun getValue(
      thisRef : Any?,
      prop : KProperty<*>
   ) : T {
      println("${prop.name} returned value $value")
      return value
   }

   operator fun setValue(
      thisRef : Any?,
      prop : KProperty<*>,
      newValue : T
   ) {
      val name = prop.name
      println("$name changed from $value to $newValue")
      value = newValue
   }
}

LoggingProperty 클래스는 프로퍼티의 값을 가져오고 설정할 때 로깅을 수행합니다. 이를 통해 변수의 값 변경과 값을 읽을 때 로그를 남길 수 있습니다.
main 함수에서는 LoggingProperty 클래스를 사용하여 test라는 프로퍼티를 정의하고, 초기값으로 100을 할당합니다. 이후에 test 값을 읽고 출력합니다.

public final class MainKt {
   // $FF: synthetic field
   static final KProperty[] $$delegatedProperties = new KProperty[]{Reflection.property0(new PropertyReference0Impl(MainKt.class, "test", "<v#0>", 1))};

   public static final void main() {
      LoggingProperty var10000 = new LoggingProperty(100);
      KProperty var1 = $$delegatedProperties[0];
      LoggingProperty test = var10000;
      int var2 = ((Number)test.getValue((Object)null, var1)).intValue();
      System.out.println(var2);
   }

   // $FF: synthetic method
   public static void main(String[] var0) {
      main();
   }
}

컴파일된 Kotlin 코드는 Java 코드로 디컴파일될 때, getValuesetValue 메서드가 호출되는 형태로 변환됩니다. 또한 $delegateProperties 배열에 프로퍼티와 연결된 KProperty 객체가 생성되어 저장됩니다.