Home > Software design >  kotlin: how to use KProperty2?
kotlin: how to use KProperty2?

Time:02-05

I understand that KProperty1 represents a property on a class, such as MyClass::myProperty.

I'm having trouble understand how KProperty2 should be used, or even what the concrete use case is for that pattern?

Thanks

CodePudding user response:

It's as documentation states for properties that take two receivers like extension property declared in a class.

Do note that calling extension functions and properties declared within class has be done within that class itself or through scoping functions (as done in sample below with run {}):

Example:

data class Foo(val tag : String) {
    val Int.echo
        get() = "Im extension on $this within ${this@Foo}"
}

fun propTest(){
    val foo = Foo("Baz")

    foo.run {
        println(5.echo)    // prints Im extension on 5 within Foo(tag=Baz)
    }

    val tagRef : KProperty1<Foo, String> = Foo::tag
    val echoRef : KProperty2<Foo, Int, String> = Foo::class.declaredMemberExtensionProperties.first() as KProperty2<Foo, Int, String>

    println(echoRef.get(foo, 7))  // prints Im extension on 7 within Foo(tag=Baz)
}

I don't know if it's possible to directly reference those extensions (Int::echo within class scope just causes error) that's why I used declaredMemberExtensionProperties (which is actually a List<Kproperty2<Foo, *, *>>) to fetch it.

  •  Tags:  
  • Related