當Android遇上Kotlin — Day 1

Locus Yu
Locus Yu
Aug 29, 2017 · 5 min read

基礎概念

  • val用來表示常數,類似Java的final,不可以被改變的變數
  • var用來表示變數,可以對他進行數值的改變

新觀念:盡可能地去使用val來作為宣告的變數,或函數中的參數,這樣可以幫助程式在使用變數時能更清楚了解哪些變數是可被改變,而透過編譯器來進行判斷

  • 函數改用fun,參數型態寫在參數後方
  • 函數不一定需要將他放在一個class中,每行結束不再需要分號(;)
  • 回傳值型態設定在函數後方,若為void則使用Unit或直接省略
  • 當function的內容僅使用一個表達式時,可使用“=[表達式]”來簡寫
fun main(args: Array<String>) {
print(sayHello())
}
fun sayHello(): String {
return "Hello, world!"
}
fun max(a: Int, b: Int): Int = if (a > b) a else b
  • 字串模板
In Java
String name = "Locus";
輸出:"Hello," + name + "!";
In Kotlin
val name: String = "Locus"
輸出:"Hello, $name!"
另外也可以使用複雜的表達式
輸出:"Hello, ${if(args.size() > 0) args[0] else "someone"}!"
  • 類別屬性
  • getter & setter
// 基本款簡單的人物類別
class Person {
val name: String
var gender: Int // 0: male, 1: female, 2: other
}
創建人物
val person = Person("Locus", 0)
print(person.name) // Locus
print(person.gender) // 0
修改屬性,讓Locus變性
person.gender = 1
print(person.gender) // 1
// 客製款class Person {
var name: String = ""
get() = field.toUpperCase()
set(value) = {
field = value
}
}
person.name = "Locus"
print(person.name) // LOCUS
  • 列舉
enum class Color(val r: Int, val g: Int, val b: Int){
YELLOW(255, 255, 0), GREEN(0, 255, 0), RED(255, 0, 0); //需要分號
fun rgb() = (r * 256 + g) * 256 + b
}
  • switch改用when
fun getWarmColor(color: Color) = when(color) {
Color.RED, Color.ORANGE, Color.YELLOW -> "warm"
Color.GREEN -> "neutral"
Color.BLUE, Color.INDIGO, Color.VIOLET -> "cold"
}
// 另外可以透過導入Color類別,來簡化程式碼
import com.example.Color.*
fun getWarmColor(color: Color) = when(color) {
RED, ORANGE, YELLOW -> "warm"
GREEN -> "neutral"
BLUE, INDIGO, VIOLET -> "cold"
}
// 對任何對象都能使用when來進行判斷
fun mixColor(color1: Color, color2: Color) =
when(setOf(color1, color2)) {
setOf(RED,YELLOW) -> "ORANGE"
setOf(YELLOW, BLUE) -> "GREEN"
else -> throw Exception("Dirty Color")
}
// when與if的組合技
fun evalWithLogging(e: Expr): Int =
when (e) {
is Num -> {
println("num: ${e.value}")
e.value
}
is Sum -> {
val left = evalWithLogging(e.left)
val right = evalWithLogging(e.right)
println("sum: $left + $right")
left + right
}
else -> throw IllegalArgumentException("Unknown expression")
}
  • for加入了Rang的概念
1..10 // 1~10
10 downTo 1 // 10~1
1..10 step 2 // 1~10間隔2
1 until 10 // 1~9
  • public static final 其實就是Kotlin中的const
const val String SEPARATOR = “|”
  • instanceof在Kotlin中改用is來表示

)
Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade