How to implement Builder pattern in Kotlin?

后端 未结 13 1609
半阙折子戏
半阙折子戏 2020-11-29 16:18

Hi I am a newbie in the Kotlin world. I like what I see so far and started to think to convert some of our libraries we use in our application from Java to Kotlin.

T

13条回答
  •  庸人自扰
    2020-11-29 17:05

    I implemented a basic Builder pattern in Kotlin with the follow code:

    data class DialogMessage(
            var title: String = "",
            var message: String = ""
    ) {
    
    
        class Builder( context: Context){
    
    
            private var context: Context = context
            private var title: String = ""
            private var message: String = ""
    
            fun title( title : String) = apply { this.title = title }
    
            fun message( message : String ) = apply { this.message = message  }    
    
            fun build() = KeyoDialogMessage(
                    title,
                    message
            )
    
        }
    
        private lateinit var  dialog : Dialog
    
        fun show(){
            this.dialog= Dialog(context)
            .
            .
            .
            dialog.show()
    
        }
    
        fun hide(){
            if( this.dialog != null){
                this.dialog.dismiss()
            }
        }
    }
    

    And finally

    Java:

    new DialogMessage.Builder( context )
           .title("Title")
           .message("Message")
           .build()
           .show();
    

    Kotlin:

    DialogMessage.Builder( context )
           .title("Title")
           .message("")
           .build()
           .show()
    

提交回复
热议问题