經(jīng)常聽人說 “java已死糠悯,jvm永存!”帮坚,我對此也是深信不疑妻往。晚上抽時間看了看Kotlin,不覺已迷失在Swift和Kotlin之中無法自拔试和,故做個基礎(chǔ)語法速通讯泣。
函數(shù)
//指定函數(shù)返回值為Int
fun sum(a: Int, b: Int): Int {
return a + b
}
//自動推斷返回值類型為 Int
fun sum1(a: Int, b: Int) = a + b
//這種寫法相當(dāng)于
fun sum1(a: Int, b: Int): Int {
return a + b
}
//無返回值
fun printSum(a: Int, b: Int): Unit {
println(a + b)
}
//無返回值 可省略Unit
fun printSum2(a: Int, b: Int) {
println(a + b)
}
//函數(shù)參數(shù)默認(rèn)值
fun foo(a: Int = 0, b: String = "abc") { ... }
常量和變量:常量關(guān)鍵字是val,變量關(guān)鍵字是var
//常量
val age: Int = 2
//自動推測類型為 Int
val age2 = 3
//先定義后初始化,需要寫返回值類型
fun test() {
val age3: Int
age3 = 8}
//變量fun test2() {
var x = 5
x += 1
}
字符串
//字符串模板 ${}
fun sayHello(name: String) {
println("Hello ${name}!")
}
數(shù)組阅悍,集合好渠,Map
//初始化一個list
val list = listOf<Char>('a', 'b', 'c')
//初始化一個map
val map = mapOf<String, Int>("a" to 1, "b" to 2, "c" to 3)
//List Map取值
println(list[2])
println(map["a"])
map["b"] = 5
//集合操作
fun collections(names: List<String>) {
//1.
for (name in names)
print(name)
//2.
if ("jtf" in names) {
print("yes")
}
//3.
names.filter { it.startsWith("j") }
.sortedBy { it }
.map { it.toUpperCase() }
.forEach { print(it) }
}
//集合過濾
fun foo2(names: List<Int>) {
val positives = names.filter { x -> x > 0 }
//更短的寫法
val positives2 = names.filter { it > 0 }
}
//遍歷 map
fun foo3(map: Map<String, String>) {
for((k, v) in map) {
println("$k -> $v")
}
}
if else
//if語句
fun max(a: Int, b: Int): Int {
if (a > b)
return a
else
return b
}
//if 作為表達式fun max2(a: Int, b: Int) = if (a > b) a else b
//if賦值語句
fun foo(param: Int) {
val result = if (param == 1) {
"one"
} else if (param == 2) {
"two"
} else {
"three"
}
}
循環(huán)
//for循環(huán)
fun test3(persons: List<String>) {
for (person in persons)
println(person)
//or
for (i in persons.indices)
println(persons[i])
}
//while循環(huán)
fun test4(persons: List<String>) {
var i = 0
while (i < 4)
println(persons[i++])
}
when表達式,與switch類似
//when表達式
fun cases(obj: Any) {
when(obj) {
1 -> print("One")
"hello" -> print("Greeting")
is Long -> print("Long")
!is String -> print("Not a String")
else -> print("Unknown")
}
}
//返回 when
fun transform(color: String): Int {
return when (color) {
"Red" -> 0
"Green" -> 1
"Blue" -> 2
else -> throw IllegalArgumentException("Invalid color param value")
}
}
fun transform2(color: String): Int = when (color) {
"Red" -> 0
"Green" -> 1
"Blue" -> 2
else -> throw IllegalArgumentException("Invalid color param value")
}
使用范圍
//使用范圍
fun range(a: Int, b: Int) {
//1.
if(a in 1..b-1) {
print("ok")
}
//2.
for (x in 1..5)
print(x)
}
擴展類的方法
//擴展類方法
fun String.showAuthor () {
print("姜小碼")
}
fun test5() {
"abc".showAuthor();
}
//從此节视,所有String就有了 .showAuthor()方法
with關(guān)鍵字作用
//在一個類里用'with'關(guān)鍵字執(zhí)行多個方法
class Turtle {
fun penDown() {}
fun penUp() {}
fun turn(degrees: Double) {}
fun forward(pixels: Double) {}
}
fun test6() {
val myTurtle = Turtle()
with(myTurtle) {
//draw a 100 pix square
penDown()
for(i in 1..4) {
forward(100.0)
turn(90.0)
}
penUp()
}
}
使用可為空的值和null檢查
fun parseInt(str: String): Int? {
return null
}
// if not null shorthand
fun fileTest() {
var files = File("Test").listFiles()
println(files?.size)
//為空賦默認(rèn)值
println(files?.size ?: "empty")
//為空時執(zhí)行默認(rèn)操作
println(files?.size ?: throw IllegalStateException("files is empty"))
//不為空時執(zhí)行,為空時不執(zhí)行
files?.let {
println(files.size)
}
}
類型檢查和自動類型轉(zhuǎn)換
fun getStringLength(obj: Any): Int? {
if (obj is String)
//'obj' 在該if分支下自動轉(zhuǎn)成 'String'
return obj.length
// 'obj'的類型在類型檢查分支外仍為 'Any'
return null
}
main方法的寫法
fun main(args: Array<String>) {
println("Hello World!")
}
簡單看了Kotlin發(fā)現(xiàn)拳锚,Swift真是借鑒了各種語言的長處,相信用不了幾年寻行,我大Swift姜一統(tǒng)天下霍掺!??