Raymond Chenon
Raymond Chenon

Reputation: 12662

Kotlin setter with multiple arguments

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 ?

Upvotes: 5

Views: 1795

Answers (2)

Sergei Zarochentsev
Sergei Zarochentsev

Reputation: 827

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

Upvotes: 4

Matthew Layton
Matthew Layton

Reputation: 42229

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 */ }

Upvotes: 5

Related Questions