在Java中的Builder模式中经常会使用连续引用来方便SDK调用,如下:
// Java
new Builder()
.setTitle("title")
.setTitleColor(Color.RED)
.setSubtitle("subtitle")
.setSubtitleColor(Color.GRAY)
.build();
但这个模式在Kotlin下怎么实现呢?
定义
// Kotlin
class MapBuilder {
fun setTitle(title: String): Builder = this.apply {
// save title
}
fun setSubtitle(title: String): Builder = this.apply {
// save subtitle
}
fun build(): Map = mapOf(
"title" to xxx,
"subtitle" to xxx
)
}
使用
// Kotlin
MapBuilder()
.setTitle("This is title")
.setSubtitle("this is subtitle")
.build()
网友评论