Fluent methods for data class in kotlin

后端 未结 3 1005
旧巷少年郎
旧巷少年郎 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 05:55

    If don't need to return anything but Name, you can just do it like this instead:

    data class Name(var firstName: String, var lastName: String)
    
    fun foo() {
        val name = ...
        name.apply {
            firstName = ...
            lastName = ...
        }
    }
    

    or another example:

    CorrutOfficeAccount(....).apply {
        method1()
        addCollectedFee(20000)
        method3()
    }
    

    Inside the function (what's inside the curly braces) passed to apply, this is the object apply was called on, which makes it possible to refer to member functions and properties like firstName without writing name.firstName.

    If you're not happy with this: It's not possible to make the actual setter return something, however you can of course just define a method with a different name and make that return something.

提交回复
热议问题