過去一年,使用 Kotlin 來爲安卓開發的人愈來愈多。即便那些如今尚未使用這個語言的開發者,也會對這個語言的精髓產生共鳴,它給如今 Java 開發增長了簡單而且強大的範式。Jake Wharton 在他的 Øredev 的討論中,提到了 Kotlin 是如何經過提高安卓開發的語言特性和設計模式來解決這些嚴重的問題,經過這些方法你能夠清除那些無用的 API 還有無效代碼。充分利用擴展特性來解決你的開發中的模板性代碼的問題!java
1
2
3
|
fun sum(a: Int, b: Int): Int {
return
a + b
}
|
1
|
fun sum(a: Int, b: Int) = a + b
|
1
2
3
|
fun main(args: Array<
string
>) {
println(
"Args: $args"
)
}</
string
>
|
1
2
|
val name =
"Jake"
val people: List<
string
> = ArrayList()</
string
>
|
1
2
3
4
5
|
static
boolean
isTuesday(Date date) {
return
date.getDay() ==
2
;
}
boolean
tuesday = DateUtils.isTuesday(date);
|
1
2
3
4
|
static
boolean
IsTuesday(
this
DateTime date)
{
return
date.DayOfWeek == DayOfWeek.Tuesday;
}
|
1
2
3
4
5
|
fun Date.isTuesday(): Boolean {
return
getDay() == 2
}
val tuesday = date.isTuesday();
|
1
|
fun Date.isTuesday() = day == 2
|
1
2
3
4
5
|
{ x, y -> x + y }
val sum: (Int, Int) -> Int = { x, y -> x + y }
val sum = { x: Int, y: Int -> x + y }
|
1
2
3
4
5
6
|
func apply(one: Int, two: Int, func: (Int, Int) -> Int): Int {
return
func(one, two)
}
val sum = apply(1, 2, { x, y -> x + y })
val difference = apply(1, 2, { x, y -> x - y })
|
1
2
|
val sum = apply(1, 2) { x, y -> x + y }
val difference = apply(1, 2) { x, y -> x - y }
|
01
02
03
04
05
06
07
08
09
10
11
12
|
fun <t> List<t>.filter(predicate: (T) -> Boolean): List<t> {
val newList = ArrayList<t>()
for
(item
in
this
) {
if
(predicate(item)) {
newList.add(item)
}
}
return
newList
}
val names = listOf(
"Jake"
,
"Jesse"
,
"Matt"
,
"Alec"
)
val jakes = names.filter { it ==
"Jake"
}</t></t></t></t>
|
1
2
3
4
5
|
fun Any.
lock
(func: () -> Unit) {
synchronized (
this
) {
func()
}
}
|
01
02
03
04
05
06
07
08
09
10
11
12
13
14
|
data
class
Lock<t>(
private
val obj: T) {
public
fun acquire(func: (T) -> Unit) {
synchronized (obj) {
func(obj)
}
}
}
val readerLock = Lock(JsonReader(stream))
// Later
readerLock.acquire {
println(it.readString())
}</t>
|
1
|
val notEmpty: (String) -> Boolean { !it.isEmpty() }
|
1
2
3
4
5
6
7
|
db.beginTransaction();
try
{
db.delete(
"users"
,
"first_name = ?"
,
new
String[] {
"Jake"
});
db.setTransactionSuccessful();
}
finally
{
db.endTransaction();
}
|
01
02
03
04
05
06
07
08
09
10
11
12
13
|
fun SQLiteDatabase.inTransaction(func: (SQLiteDatabase) -> Unit) {
beginTransaction()
try
{
func(
this
)
setTransactionSuccessful()
}
finally
{
endTransaction()
}
}
db.inTransaction {
it.db.delete(
"users"
,
"first_name = ?"
, arrayOf(
"Jake"
))
}
|
1
2
3
4
|
db.inTransaction {
it.db.delete(
"users"
,
"first_name = ?"
, arrayOf(
"Jake"
))
}<font face=
"Tahoma, Arial, Helvetica, snas-serif"
><span style=
"font-size: 14px; white-space: normal;"
>
</span></font>
|
1
|
inline fun SQLiteDatabase.inTransaction(func: SQLiteDatabase.() -> Unit) { ... }
|
01
02
03
04
05
06
07
08
09
10
11
12
13
14
|
verticalLayout {
padding = dip(30)
editText {
hint =
"Name"
textSize = 24f
}
editText {
hint =
"Password"
textSize = 24f
}
button(
"Login"
) {
textSize = 26f
}
}
|