FROM JAVA BUILDERS TO KOTLIN DSLS kotlinexpertise.com/java-builde… [翻译中]
Introduction DSLs – Domain Specific Languages – are an ever trending topic in Kotlin circles. They allow us to flex some of the most exciting language features while accomplishing more readable and maintainable solutions in our code.
Today I’d like to show you how to implement a certain kind of DSL – we’re going to be wrapping an existing Java Builder in Kotlin. No doubt you’ve come across the builder pattern in Java before, for example if you’re an Android developer, you must’ve used an AlertDialog.Builder, an OkHttpClient.Builder, or a Retrofit.Builder at some point. Wrapping a builder like this is a good exercise in just pure DSL design. All you have to worry about is designing the API you provide with your wrapper, since all the implementation for whatever your DSL provides its users is already done inside the builder!
简介
DSL – Domain Specific Language首字母缩写,领域特定语言 – 在Kotlin的圈子曾经是个大热点。它们允许我们灵活使用一些最令人兴奋的语言特性,同时在代码中实现更具可读性和可维护性的解决方案。 今天,我将像你展示如何实现一种DSL - 我们将用Kotlin来包装一个Java Builder.毫无疑问的是,你肯定曾经用到过建造者模式。举个例子,假如你是一个Android开发者,你肯定曾经用到过AlertDialog.Builder,OkHttpClient.Builder或者Retrofit.Builder。如果我们想练习设计一个简单的DSL,包装一个类似上边提到的builder是最好的。你只需要关心的是如何更好提供API,因为所有的具体实现都在builder中实现了。
Our example case It just so happens that I’m the creator and maintainer of a library that does this very thing, and a small part of its implementation is what we’re going to be using as our example. The original library is the wonderful and hugely popular MaterialDrawer by Mike Penz, which allows you to create complex, good looking, and customized navigation drawers in your application, all via various Builder objects in Java, with no XML writing involved on your part. This is what my library, MaterialDrawerKt provides a convenient Kotlin DSL wrapper for.
我们的样例
刚巧我是一个开源库的创建者和维护者,这个库的一部分实现刚好可以用作我们这次的例子。这个库来源于Mike Penz写的一个非常强大的开源库-MaterialDrawer。这个库让使用者在自己的应用中创建复杂,美观,定制化的侧边导航。他由一些列Java写的建造者对象来实现,不需要写XML。而我创建和维护的这个库-MaterialDrawerKt,为其提供了方便使用的Kotlin DSL包装。
DrawerBuilder()
.withActivity(this)
.withTranslucentStatusBar(false)
.withDrawerLayout(R.layout.material_drawer_fits_not)
.addDrawerItems(
PrimaryDrawerItem()
.withName("Home")
.withDescription("Get started here!"),
PrimaryDrawerItem()
.withName("Settings")
.withDescription("Tinker around")
)
.withOnDrawerItemClickListener { view, position, drawerItem ->
when(position) {
0 -> toast("Home clicked")
1 -> toast("Settings clicked")
}
true
}
.withOnDrawerListener(object: Drawer.OnDrawerListener {
override fun onDrawerSlide(drawerView: View?, slideOffset: Float) {
// Empty
}
override fun onDrawerClosed(drawerView: View?) {
toast("Drawer closed")
}
override fun onDrawerOpened(drawerView: View?) {
toast("Drawer opened")
}
})
.build()
复制代码