Fluent methods for data class in kotlin

后端 未结 3 974
旧巷少年郎
旧巷少年郎 2021-01-13 05:09

We are familiar with fluent interfaces for calling methods in java and other programming languages. For eg:

Picasso.with(this).load(url).into(imageView);
         


        
3条回答
  •  小鲜肉
    小鲜肉 (楼主)
    2021-01-13 06:00

    Thanks to Zsmb13 and Christin for the answer, but if someone wants to use immutable fields I have another solution

    data class Foo(val fooString: String = "", val fooInt: Int = 0) {
        fun increaseTwo() = copy(fooInt = fooInt + 2)
        fun increaseThree() = copy(fooInt = fooInt + 3)
    }
    

    And you can use it like this

    println( Foo("foo",2).increaseTwo().increaseThree())
    

    Output :

    Foo(fooString=foo, fooInt=7)
    

提交回复
热议问题