美文网首页程序员
JVM语言Kotlin Getting started

JVM语言Kotlin Getting started

作者: 姜小码 | 来源:发表于2016-01-20 23:26 被阅读126次

经常听人说 “java已死,jvm永存!”,我对此也是深信不疑。晚上抽时间看了看Kotlin,不觉已迷失在Swift和Kotlin之中无法自拔,故做个基础语法速通。

函数

//指定函数返回值为Int
fun sum(a: Int, b: Int): Int {
    return a + b
}

//自动推断返回值类型为 Int
fun sum1(a: Int, b: Int) = a + b
//这种写法相当于
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)
}

//函数参数默认值
fun foo(a: Int = 0, b: String = "abc") { ... }

常量和变量:常量关键字是val,变量关键字是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}!")
}

数组,集合,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"
    }
}

循环


//for循环
fun test3(persons: List<String>) {
    for (person in persons)
        println(person)
    //or
    for (i in persons.indices)
        println(persons[i])
}

//while循环
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关键字作用

//在一个类里用'with'关键字执行多个方法
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)
    //为空赋默认值
    println(files?.size ?: "empty")
    //为空时执行默认操作
    println(files?.size ?: throw IllegalStateException("files is empty"))
    //不为空时执行,为空时不执行
    files?.let {
        println(files.size)
    }
}

类型检查和自动类型转换

fun getStringLength(obj: Any): Int? {
    if (obj is String)
        //'obj' 在该if分支下自动转成 'String'
        return obj.length
    // 'obj'的类型在类型检查分支外仍为 'Any'
    return null
}

main方法的写法

fun main(args: Array<String>) {
     println("Hello World!")
}

简单看了Kotlin发现,Swift真是借鉴了各种语言的长处,相信用不了几年,我大Swift姜一统天下!😊

相关文章

网友评论

    本文标题:JVM语言Kotlin Getting started

    本文链接:https://www.haomeiwen.com/subject/eeelkttx.html