Kotlin已經(jīng)被google列為Android官方的一級開發(fā)語言赚哗,此文章是在自己學(xué)習(xí)觀看google io 2017 和閱讀Kotlin官方文檔的時候盾戴,記錄下Kotlin的一些write less的Tips.
#常規(guī)寫法:
fun sum(a: Int, b: Int): Int {
return a + b
}
#Write less:
fun sum(a:Int, b:Int) = a + b
- **Tip2:使用when關(guān)鍵字 **
#相對于java常規(guī)的switch case匹颤,when提供了更加靈活的方式:
fun describe(obj: Any): String =
when (obj) {
1 -> "One"
"Hello" -> "Greeting"
is Long -> "Long"
!is String -> "Not a string"
else -> "Unknown"
}
fun main(args: Array<String>) {
println(describe(1))
println(describe("Hello"))
println(describe(1000L))
println(describe(2))
println(describe("other"))
}
- Tip3:for循環(huán)中使用in,step,downTo
#組合使用in,step,downTo
fun main(args: Array<String>) {
for (x in 1..10 step 4) {
print(x)
}
print(" - ")
for (x in 9 downTo 0 step 3) {
print(x)
}
}
Result:159 - 9630
- Tip4:使用lambda表達(dá)式來操作集合
#在集合中使用filter,map,sortBy等關(guān)鍵字
fun main(args: Array<String>) {
val fruits = listOf("banana", "avocado", "apple", "kiwi")
fruits
.filter { it.startsWith("a") }
.sortedBy { it }
.map { it.toUpperCase() }
.forEach { println(it) }
}
Result:
APPLE
AVOCADO
when (x) {
is Foo -> ...
is Bar -> ...
else -> ...
}
val list = listOf("a", "b", "c")
val map = mapOf("a" to 1, "b" to 2, "c" to 3)
object Resource {
val name = "Name"
}
val data = ...
val email = data["email"] ?: throw IllegalStateException("Email is missing!")
- Tip9:在return中使用when關(guān)鍵字
fun transform(color: String): Int {
return when (color) {
"Red" -> 0
"Green" -> 1
"Blue" -> 2
else -> throw IllegalArgumentException("Invalid color param value")
}
}
- Tip10:使用with關(guān)鍵字調(diào)用多個方法
class Turtle {
fun penDown()
fun penUp()
fun turn(degrees: Double)
fun forward(pixels: Double)
}
val myTurtle = Turtle()
with(myTurtle) { //draw a 100 pix square
penDown()
for(i in 1..4) {
forward(100.0)
turn(90.0)
}
penUp()
}
#普通寫法
var max: Int
if (a > b) {
max = a
} else {
max = b
}
#簡寫
val max = if (a > b) a else b
var stringRepresentation: String
get() = this.toString()
set(value) {
setDataFromString(value)
}
#簡寫get
val isEmpty get() = this.size == 0 // has type Boolean
operator fun ViewGroup.get(index : Int): View? = getChildAt(index)
operator fun ViewGroup.minusAssign(child: View) = removeView(child)
operator fun ViewGroup.plusAssign(child: View) = addView(child)
#重載[] - +,你就可以使用下面的方法來操作view
val views = //...
val first = views[0]
views -= first
view += first
#java的方式
MainActivity.java
SQLiteDatabase db = //.....
db.beginTransacation();
try {
db.delete("user","first_name = ?",new String[] {"jake"};
db.setTransactionSuccessful();
} finally {
db.endTransaction();
}
#kotlin的inline函數(shù)
##Database.kt
inline fun SQLiteDatabase.transaction(body : () -> Unit ) {
beginTransaction()
try {
body()
setTransaction()
} finally {
endTransaction()
}
}
##MainActivity.kt
val db = //....
db.transaction = {
db.delete("users", "first_name = ?",arrayOf("jake"))
}
private val name by Delegate.observable("jane") {old, new, prop - >
println("Name changed form $old to $new )
}