One can easily set a setter like for data
How to set more than 1 value from the same method ?
I use the inelegant method setData
to accomplish it.
class MyClass{
var data = listOf<GithubRepo>() // individual setter
set(value) {
field = value
}
lateinit var listener: (GithubRepo) -> Unit // lambda
// classical setter like in Java
fun setData( data: List<GithubRepo>, listener: (GithubRepo) -> Unit): Unit{
this.data = data
this.listener = listener
}
}
Is there a more Kotlin way to set multiple variables from the method ?
That's not possible due to the way that setter functions work - they only take a single argument. Even if you think about the usage of a setter with multiple arguments, it wouldn't look right:
x.data = items, { /** listener impl */ }
If you really wanted to, you could group your arguments into a single object:
x.data = Wrapper(items, { /** listener impl */ })
But even that suggestion isn't nice. The nicest in my opinion is what you consider to be inelegant, using a Java style setter (which isn't a typical setter since it has multiple arguments), but at least Kotlin gives you a nicer call syntax:
x.setData(items) { /** listener impl */ }
What about using pairs?
class MyClass{
lateinit var data : Pair<List<GithubRepo>, (GithubRepo) -> Unit>
}
This will force to set both of list and listener simultaneously.
But I think your solution with classical setter is the best possible and readable
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With