Kotlin已经被google列为Android官方的一级开发语言,此文章是在自己学习观看google io 2017 和阅读Kotlin官方文档的时候,记录下Kotlin的一些write less的Tips.
#常规写法:
fun sum(a: Int, b: Int): Int {
return a + b
}
#Write less:
fun sum(a:Int, b:Int) = a + b
#相对于java常规的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循环中使用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
#在集合中使用filter,map,sortBy等关键字
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!")
fun transform(color: String): Int {
return when (color) {
"Red" -> 0
"Green" -> 1
"Blue" -> 2
else -> throw IllegalArgumentException("Invalid color param value")
}
}
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函数
##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 )
}