第三十节 DSL中集合

如果要实现这种定义方式呢?(可以有多个地址,类似淘宝的收货地址)

person {
        name = "张三"
        age = 10
        addresses{
            address {
                city = "北京市"
                street = "北三环街道"
                number = 100000
            }
            address {
                city = "北京市"
                street = "北三环街道"
                number = 100000
            }
        }

    }

代码实现:

fun main(args: Array) {


    var p=person {
        name = "张三"
        age = 10
        addresses{
            address {
                city = "北京市"
                street = "北三环街道"
                number = 100000
            }
            address {
                city = "北京市"
                street = "北三环街道"
                number = 100000
            }
        }
    }
    println(p)


}

fun PersonBuilder.addresses(block:ArrayList
.()->Unit) { //需要定义个集合,赋值给personBuilder的addresses var list=ArrayList
() block.invoke(list) this.addresses=list } /** * 定义address方法 */ fun ArrayList
.address(block:AddressBuilder.()->Unit) { var addressBuilder=AddressBuilder() block.invoke(addressBuilder) this.add(Address(addressBuilder.city,addressBuilder.street,addressBuilder.number)) } /** * 首先定义一个方法person,这个返回定义好的Person对象 */ fun person(block:PersonBuilder.()->Unit):Person { var personBuilder=PersonBuilder() block.invoke(personBuilder) return Person(personBuilder.name,personBuilder.age,personBuilder.addresses) } /** * 我们直接定义成data类型,便于打印 * 城市、街道、街道号 */ data class Address(val city:String?,val street:String?,val number:Int?) data class AddressBuilder(var city:String?=null,var street:String?=null,var number:Int?=null) /** * 姓名、年龄、地址 */ data class Person(val name:String?,val age:Int?,val addresses: ArrayList
?) data class PersonBuilder(var name:String?=null,var age:Int?=null,var addresses: ArrayList
?=null)

输出:


image.png

你可能感兴趣的:(第三十节 DSL中集合)