今天來學習下基本語法,參考了官方文檔
包
package com.kotlin
導入
import關鍵字
import java.util*
類型的聲明
Kotlin使用var 定義變量
var a:Int = 1
var b:Double = 2
使用val 定義常量
val c:Char = "你好"
函數
函數聲明
Kotlin使用fun關鍵字作爲函數聲明
-
fun double(a:Int) {
-
return 2*a
-
}
函數用法
傳統方式:
cal.double(2) //創建cal實例,並且調用double
函數參數
函數參數使用pascal定義法,即name:type。參數之間使用逗號隔開,參數必須是顯式類型
-
fun haha(hao:Char) : Char {
-
...
-
}
默認參數
函數可以有默認值,當省略參數時,使用默認值,以下引用官方手冊
-
fun read(b: Array<Byte>, off: Int = 0, len: Int = b.size) {
-
……
-
}
默認值通過類型後面的 = 及給出的值來定義。覆蓋方法總是使用與基類型方法相同的默認參數值。 當覆蓋一個帶有默認參數值的方法時,必須從簽名中省略默認參數值:
-
open class A {
-
open fun foo(i: Int = 10) { …… }
-
}
-
-
class B : A() {
-
override fun foo(i: Int) { …… }
-
}
如果一個默認參數在一個無默認值的參數之前,那麼該默認值只能通過使用命名參數調用該函數來使用:
-
fun foo(bar: Int = 0, baz: Int) { }
-
-
foo(baz = 1)
不過如果最後一個
lambda表達式參數從括號外傳給函數函數調用,那麼允許默認參數不傳值:
-
fun foo(bar: Int = 0, baz: Int = 1, qux: () -> Unit) { }
-
-
foo(1) { println("hello") }
-
foo { println("hello") }
命名參數
可以在調用函數時使用命名的函數參數。當一個函數有大量的參數或默認參數時這會非常方便。
給定以下函數
-
fun reformat(str: String,
-
normalizeCase: Boolean = true,
-
upperCaseFirstLetter: Boolean = true,
-
divideByCamelHumps: Boolean = false,
-
wordSeparator: Char = ' ') {
-
……
-
}
我們可以使用默認參數來調用它
-
reformat(str, true, true, false, '_')
使用命名參數我們可以使代碼更具有可讀性
-
reformat(str,
-
normalizeCase = true,
-
upperCaseFirstLetter = true,
-
divideByCamelHumps = false,
-
wordSeparator = '_'
-
)
並且如果我們不需要所有的參數
-
reformat(str, wordSeparator = '_')
定義函數
定義一個有兩個Int類型的入參,及返回類型是Int。
-
fun sum1(a:Int,b:Int) : Int {
-
return a + b
-
}
定義一個將表達式作爲函數體、返回值類型爲自動推斷的函數
-
fun sum2(a:Int,b:Int) = a + b
定義一個函數,返回無意義的值
-
fun printSum1(a: Int, b: Int): Unit {
-
println("sum of $a and $b is ${a + b}")
-
}
其中${dosth}指的是內插語句