Kotlin出來已經很久了,之前就一直說要學習學習,一直也沒有行動。從今天開始,首先簡單的走一下語法。
Kotlin支持的數據類型:
基本數據類型如下
Type | Bit width |
Double | 64 |
Float | 32 |
Long | 64 |
Int | 32 |
Short | 16 |
Byte | 8 |
toByte(): Byte
toShort(): Short
toInt(): Int
toLong(): Long
toFloat(): Float
toDouble(): Double
toChar(): Char
還有字符類型:Char,布爾類型:Boolean,還有一個比較特殊的類型數組類型:Array.字符串:String。
對於Array數組類型:
可以通過庫函數arrayof()來創建一個數組並傳遞元素值給它:如arrayof(1,2,3)這樣就創建了array[1,2,3].或者通過庫函數arrayofNulls()可以創建一個指定大小、元素都爲空的數組。
控制流:
- If 在 Kotlin 中, if 是一個表達式,即它會返回一個值。因此就不需要三元運算符(條件 ? 然
後 : 否則) // 作爲表達式 val max = if (a > b) a else b - When when在kotlin中,我感覺還是比較高大上的一個了。when取代了C語言中是switch。
when (x) { 1 -> print("x == 1") 2 -> print("x == 2") else -> { // 注意這個塊 print("x is neither 1 nor 2") 如果很多分支需要用相同的方式處理,則可以把多個分支條件放在一起,用逗號分隔:when (x) { 0, 1 -> print("x == 0 or x == 1") else -> print("otherwise") 我們也可以檢測一個值在( in )或者不在( !in )一個區間或者集合中: when (x) { in 1..10 -> print("x is in the range") in validNumbers -> print("x is valid") !in 10..20 -> print("x is outside the range") else -> print("none of the above")} 另一種可能性是檢測一個值是( is )或者不是( !is )一個特定類型的值。 val hasPrefix = when(x) { is String -> x.startsWith("prefix")
else -> false }
-
For循環。
-
While或者do...While
-
Break和Continue