Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Kotlin setter with multiple arguments

Tags:

setter

kotlin

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 ?

like image 711
Raymond Chenon Avatar asked Jan 01 '23 01:01

Raymond Chenon


2 Answers

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 */ }
like image 80
Matthew Layton Avatar answered Jan 04 '23 17:01

Matthew Layton


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

like image 33
ZSergei Avatar answered Jan 04 '23 17:01

ZSergei