How to implement Builder pattern in Kotlin?

后端 未结 13 1562
半阙折子戏
半阙折子戏 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:22
    class Foo private constructor(@DrawableRes requiredImageRes: Int, optionalTitle: String?) {
    
        @DrawableRes
        @get:DrawableRes
        val requiredImageRes: Int
    
        val optionalTitle: String?
    
        init {
            this.requiredImageRes = requiredImageRes
            this.requiredImageRes = optionalTitle
        }
    
        class Builder {
    
            @DrawableRes
            private var requiredImageRes: Int = -1
    
            private var optionalTitle: String? = null
    
            fun requiredImageRes(@DrawableRes imageRes: Int): Builder {
                this.intent = intent
                return this
            } 
    
            fun optionalTitle(title: String): Builder {
                this.optionalTitle = title
                return this
            }
    
            fun build(): Foo {
                if(requiredImageRes == -1) {
                    throw IllegalStateException("No image res provided")
                }
                return Foo(this.requiredImageRes, this.optionalTitle)
            }
    
        }
    
    }
    
    0 讨论(0)
提交回复
热议问题