第三十節 DSL中集合

weixin_34075551發表於2018-05-31

如果要實現這種定義方式呢?(可以有多個地址,類似淘寶的收貨地址)

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

    }

程式碼實現:

fun main(args: Array<String>) {


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


}

fun PersonBuilder.addresses(block:ArrayList<Address>.()->Unit)
{
    //需要定義個集合,賦值給personBuilder的addresses
    var list=ArrayList<Address>()
    block.invoke(list)
    this.addresses=list
}

/**
 * 定義address方法
 */
fun ArrayList<Address>.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<Address>?)


data class PersonBuilder(var name:String?=null,var age:Int?=null,var addresses: ArrayList<Address>?=null)



輸出:


2607504-f15f287382fa545f.png
image.png

相關文章