FROM JAVA BUILDERS TO KOTLIN DSLS kotlinexpertise.com/java-builde… [翻译中]java
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.app
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!ide
DSL – Domain Specific Language首字母缩写,领域特定语言 – 在Kotlin的圈子曾经是个大热点。它们容许咱们灵活使用一些最使人兴奋的语言特性,同时在代码中实现更具可读性和可维护性的解决方案。 今天,我将像你展现如何实现一种DSL - 咱们将用Kotlin来包装一个Java Builder.毫无疑问的是,你确定曾经用到过建造者模式。举个例子,假如你是一个Android开发者,你确定曾经用到过AlertDialog.Builder,OkHttpClient.Builder或者Retrofit.Builder。若是咱们想练习设计一个简单的DSL,包装一个相似上边提到的builder是最好的。你只须要关心的是如何更好提供API,由于全部的具体实现都在builder中实现了。flex
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.ui
刚巧我是一个开源库的建立者和维护者,这个库的一部分实现恰好能够用做咱们此次的例子。这个库来源于Mike Penz写的一个很是强大的开源库-MaterialDrawer。这个库让使用者在本身的应用中建立复杂,美观,定制化的侧边导航。他由一些列Java写的建造者对象来实现,不须要写XML。而我建立和维护的这个库-MaterialDrawerKt,为其提供了方便使用的Kotlin DSL包装。this
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()
复制代码