比如说下面这段Java代码,如果使用Kotlin该如何写?
1public class Car {
2 private int year;
3 private String model;
4
5 private Car(Builder builder) {
6 this.year = builder.year;
7 this.model = builder.model;
8 }
9
10 public static class Builder {
11 private int year;
12 private String model;
13
14 public Builder setModel(String model) {
15 this.model = model;
16 return this;
17 }
18
19 public Builder setYear(int year) {
20 this.year = year;
21 return this;
22 }
23 public Car build() {
24 return new Car(this);
25 }
26 }
27}
在kotlin中,大多数情况都不需要生成器模式,因为kotlin支持默认参数和命名参数,比如说上面的类,在kotlin中可以这样定义。
class Car(val model: String? = null, val year: Int = 0)
实例化Car时,只需要在构造方法中设必要的参数,而其它的参数使用默认值,实现类似生成器模式的效果。
val car = Car(model = "X")
如果一定要使用生成器模式,也是可以的,比如说上面那段Java代码,改用kotlin实现如下。
1class Car private constructor(val model: String?, val year: Int) {
2
3 private constructor(builder: Builder) : this(builder.model, builder.year)
4
5 class Builder {
6 var model: String? = null
7 private set
8
9 var year: Int = 0
10 private set
11
12 fun model(model: String) = apply { this.model = model }
13
14 fun year(year: Int) = apply { this.year = year }
15
16 fun build() = Car(this)
17 }
18}
用法和Java中类似。
val car = Car.Builder().model("X").build()
上面的kotlin代码还可以使用builder DSL进行简化。
1class Car private constructor(val model: String?, val year: Int) {
2
3 private constructor(builder: Builder) : this(builder.model, builder.year)
4
5 companion object {
6 inline fun build(block: Builder.() -> Unit) = Builder().apply(block).build()
7 }
8
9 class Builder {
10 var model: String? = null
11 var year: Int = 0
12
13 fun build() = Car(this)
14 }
15}
用法和之前有一点不同。
val car = Car.build() { model = "X" }
内容