Is there any dicussion about operator functions fo...
# language-proposals
s
Is there any dicussion about operator functions for getting and setting properties? Example:
Copy code
class Builder<T> {
    operator fun <V> getProperty(key: KProperty1<T, V>): V
    operator fun <@kotlin.internal.OnlyInputTypes V> setProperty(key: KProperty1<T, V>, value: V)    
}

class MyUser(val name: String, val age: Int)

fun buildUser() {
    val userBuilder = Builder<MyUser>()

    userBuilder.name = "test"
    userBuilder.age = 132    

    // should be compiled to:
    // userBuilder.setProperty(MyUser::name, "test")
    // userBuilder.setProperty(MyUser::age, 132)   

    // @OnlyInputTypes is required to disallow userBuilder.name = 123, since R in KProperty1 is contravariant
}
Another use case is LINQ:
Copy code
class Expression<T> {
    operator fun <V> getProperty(key: KProperty1<T, V>): Expression<V>
}

fun Expression<T>.equals(other: Expression<T>): Expression<Boolean> = TODO()
fun Expression<T>.greater(other: Expression<T>): Expression<Boolean> = TODO()
fun Expression<Boolean>.and(other: Expression<Boolean>): Expression<Boolean> = TODO()

inline fun <reified T> query(predicateProvider: Expression<T>.() -> Expression<Boolean>) = TODO()

fun makeQuery() = query<MyUser> { (name == "test") and (age greater name.size) }

// lambda should be compiled to:
// (getProperty(MyUser::name) == "test") and (getProperty(MyUser::age) greater getProperty(MyUser::age).getProperty(String::size))
Second use case may be also covered by expression trees, but first likely not.
r
Personally, I don't see how that's much better than using the
get
and
set
operators, in which case it would just be:
Copy code
userBuilder["name"] = "test"
userBuilder["age"] = 132
s
in your example it is not that type safe. in the provided example you can set only properties of
MyUser
.
also ide completion will not work
r
I don't see how your proposal is any different, so I must be missing something.
Ah, wait, I misread. I see the difference.
s
you cannot call
Builder<MyUser>().setProperty(AnotherObj::anotherProp)
, only
MyUser
properties will be accepted
r
I see that now. I can't say I'm a fan of the idea, but I'm sure there are many that are (I've never particularly liked LINQ)