如何使用kotlin编写没有导入或val的DSL

时间:2019-01-18 10:22:37

标签: kotlin dsl

我正在尝试按照此处的示例https://github.com/zsmb13/VillageDSL

创建kotlin DSl

他们写道:

val volleyEnrollRequest = object : JsonObjectRequest(GET_POST_PARAM, TARGET_URL, requestJSONObject,
            Response.Listener {
                // Success Part  
            },

            Response.ErrorListener {
                // Failure Part
            }
        ) {
            // Providing Request Headers

            override fun getHeaders(): Map<String, String> {
               // Create HashMap of your Headers as the example provided below

                val headers = HashMap<String, String>()
                headers["Content-Type"] = "application/json"
                headers["app_id"] = APP_ID
                headers["app_key"] = API_KEY

                return headers
            }

            // Either override the below method or pass the payload as parameter above, dont do both 

            override fun getParams(): Map<String, String> {
               // Create HashMap of your params as the example provided below

                val headers = HashMap<String, String>()
                headers["param1"] = "param1Value"
                headers["param2"] = "param2Value"
                headers["param3"] = "param3Value"

                return headers
            }
        }

我想知道是否有办法像gradle这样写它:

val v = village {
    house {
        person {
            name = "Emily"
            age = 31
        }
        person(name = "Hannah") {
            age = 27
        }
        person("Alex", 21)
        person(age = 17, name = "Daniel")
    }
}

并自动生成导入(例如在gradle中)。

我当时正在考虑通过通配符导入和village { house { person { name = "Emily" age = 31 } person(name = "Hannah") { age = 27 } person("Alex", 21) person(age = 17, name = "Daniel") } } 来以编程方式包装文件,但是它可能会泄漏且有错误,是否有更好的方法?

1 个答案:

答案 0 :(得分:0)