0%

写给 Java 开发者的 Kotlin 教程 (13) - 最佳实践

表达式

1
2
3
4
5
6
fun getDefaultLocale2(deliveryArea: String) = when (deliveryArea.toLowerCase()) {
"germany", "austria" -> Locale.GERMAN
"usa", "great britain" -> Locale.ENGLISH
"france" -> Locale.FRENCH
else -> Locale.ENGLISH
}
1
2
3
4
5
6
7
8
9
10
11
12
13
fun getDefaultLocale(deliveryArea: String): Locale {
val deliverAreaLower = deliveryArea.toLowerCase()
if (deliverAreaLower == "germany" || deliverAreaLower == "austria") {
return Locale.GERMAN
}
if (deliverAreaLower == "usa" || deliverAreaLower == "great britain") {
return Locale.ENGLISH
}
if (deliverAreaLower == "france") {
return Locale.FRENCH
}
return Locale.ENGLISH
}

Try

1
2
3
4
5
6
val json = """{"message":"HELLO"}"""
val message = try {
JSONObject(json).getString("message")
} catch (ex: JSONException) {
json
}

对象工具类

1
2
3
4
fun String.countAmountOfX(): Int {
return length - replace("x", "").length
}
"xFunxWithxKotlinx".countAmountOfX()
1
2
3
4
5
6
object StringUtil {
fun countAmountOfX(string: String): Int{
return string.length - string.replace("x", "").length
}
}
StringUtil.countAmountOfX("xFunxWithxKotlinx")

优先使用命名参数

1
2
3
4
5
6
val config2 = SearchConfig2(
root = "~/folder",
term = "kotlin",
recursive = true,
followSymlinks = true
)
1
2
3
4
5
6
val config = SearchConfig()
.setRoot("~/folder")
.setTerm("kotlin")
.setRecursive(true)
.setFollowSymlinks(true)
StringUtil.countAmountOfX("xFunxWithxKotlinx")

不要重载默认参数

1
2
fun find(name: String, recursive: Boolean = true){
}
1
2
3
4
5
fun find(name: String){
find(name, true)
}
fun find(name: String, recursive: Boolean){
}

考虑使用 let

1
2
3
findOrder()?.let { dun(it.customer) }
//or
findOrder()?.customer?.let(::dun)
1
2
3
4
val order: Order? = findOrder()
if (order != null){
dun(order.customer)
}
来杯奶茶, 嗝~~~