kotlin---基本语法

定义包

包的声明应处于源文件顶部:

package my.demo

import java.util.*

// ……

目录与包的结构无需匹配:源代码可以在文件系统的任意位置。

参见

定义函数

带有两个 Int 参数、返回 Int 的函数:

fun sum(a: Int, b: Int): Int {
    return a + b
}
sum of 3 and 5 is 8
Target platform: JVM Running on kotlin v. 1.1.2

将表达式作为函数体、返回值类型自动推断的函数:

fun sum(a: Int, b: Int) = a + b
sum of 19 and 23 is 42
Target platform: JVM Running on kotlin v. 1.1.2

函数返回无意义的值:

fun printSum(a: Int, b: Int): Unit {
    println("sum of $a and $b is ${a + b}")
}
sum of -1 and 8 is 7
Target platform: JVM Running on kotlin v. 1.1.2

Unit 返回类型可以省略:

fun printSum(a: Int, b: Int) {
    println("sum of $a and $b is ${a + b}")
}
sum of -1 and 8 is 7
Target platform: JVM Running on kotlin v. 1.1.2

参见函数

定义局部变量

一次赋值(只读)的局部变量:

val a: Int = 1  // 立即赋值
val b = 2   // 自动推断出 `Int` 类型
val c: Int  // 如果没有初始值类型不能省略
c = 3       // 明确赋值
a = 1, b = 2, c = 3
Target platform: JVM Running on kotlin v. 1.1.2

可变变量:

var x = 5 // 自动推断出 `Int` 类型
x += 1
x = 6
Target platform: JVM Running on kotlin v. 1.1.2

参见属性和字段

注释

正如 Java 和 JavaScript,Kotlin 支持行注释及块注释。

// 这是一个行注释

/* 这是一个多行的
   块注释。 */

与 Java 不同的是,Kotlin 的块注释可以嵌套。

参见编写 Kotlin 代码文档 查看关于文档注释语法的信息。

使用字符串模板

var a = 1
// 模板中的简单名称:
val s1 = "a is $a" 
a = 2
// 模板中的任意表达式:
val s2 = "${s1.replace("is", "was")}, but now is $a"
a was 1, but now is 2
Target platform: JVM Running on kotlin v. 1.1.2

参见字符串模板

使用条件表达式

fun maxOf(a: Int, b: Int): Int {
    if (a > b) {
        return a
    } else {
        return b
    }
}
max of 0 and 42 is 42
Target platform: JVM Running on kotlin v. 1.1.2

使用 if 作为表达式:

fun maxOf(a: Int, b: Int) = if (a > b) a else b
max of 0 and 42 is 42
Target platform: JVM Running on kotlin v. 1.1.2

参见if 表达式

使用可空值及 null 检测

当某个变量的值可以为 null 的时候,必须在声明处的类型后添加 ? 来标识该引用可为空。

如果 str 的内容不是数字返回 null

fun parseInt(str: String): Int? {
    // ……
}

使用返回可空值的函数:

fun printProduct(arg1: String, arg2: String) {
    val x = parseInt(arg1)
    val y = parseInt(arg2)
    // 直接使用 `x * y` 可能会报错,因为他们可能为 null
    if (x != null && y != null) {
        // 在空检测后,x 和 y 会自动转换为非空值(non-nullable)
        println(x * y)
    }
    else {
        println("either '$arg1' or '$arg2' is not a number")
    }    
}
42either 'a' or '7' is not a numbereither 'a' or 'b' is not a number
Target platform: JVM Running on kotlin v. 1.1.2

或者

// ……
if (x == null) {
    println("Wrong number format in arg1: '${arg1}'")
    return
}
if (y == null) {
    println("Wrong number format in arg2: '${arg2}'")
    return
}
// 在空检测后,x 和 y 会自动转换为非空值
println(x * y)
42Wrong number format in arg1: 'a'Wrong number format in arg2: 'b'
Target platform: JVM Running on kotlin v. 1.1.2

参见空安全

使用类型检测及自动类型转换

is 运算符检测一个表达式是否某类型的一个实例。 如果一个不可变的局部变量或属性已经判断出为某类型,那么检测后的分支中可以直接当作该类型使用,无需显式转换:

fun getStringLength(obj: Any): Int? {
    if (obj is String) {
        // `obj` 在该条件分支内自动转换成 `String`
        return obj.length
    }
    // 在离开类型检测分支后,`obj` 仍然是 `Any` 类型
    return null
}
'Incomprehensibilities' string length is 21 '1000' string length is ... err, not a string '[java.lang.Object@6b884d57]' string length is ... err, not a string
Target platform: JVM Running on kotlin v. 1.1.2

或者

fun getStringLength(obj: Any): Int? {
    if (obj !is String) return null
    // `obj` 在这一分支自动转换为 `String`
    return obj.length
}
'Incomprehensibilities' string length is 21 '1000' string length is ... err, not a string '[java.lang.Object@6b884d57]' string length is ... err, not a string
Target platform: JVM Running on kotlin v. 1.1.2

甚至

fun getStringLength(obj: Any): Int? {
    // `obj` 在 `&&` 右边自动转换成 `String` 类型
    if (obj is String && obj.length > 0) {
        return obj.length
    }
    return null
}
'Incomprehensibilities' string length is 21 '' string length is ... err, is empty or not a string at all '1000' string length is ... err, is empty or not a string at all
Target platform: JVM Running on kotlin v. 1.1.2

参见 和 类型转换

使用 for 循环

val items = listOf("apple", "banana", "kiwi")
for (item in items) {
    println(item)
}
applebananakiwi
Target platform: JVM Running on kotlin v. 1.1.2

或者

val items = listOf("apple", "banana", "kiwi")
for (index in items.indices) {
    println("item at $index is ${items[index]}")
}
item at 0 is appleitem at 1 is bananaitem at 2 is kiwi
Target platform: JVM Running on kotlin v. 1.1.2

参见 for 循环

使用 while 循环

val items = listOf("apple", "banana", "kiwi")
var index = 0
while (index < items.size) {
    println("item at $index is ${items[index]}")
    index++
}
Target platform: JVM Running on kotlin v. 1.1.2

参见 while 循环

使用 when 表达式

fun describe(obj: Any): String =
when (obj) {
    1          -> "One"
    "Hello"    -> "Greeting"
    is Long    -> "Long"
    !is String -> "Not a string"
    else       -> "Unknown"
}
Target platform: JVM Running on kotlin v. 1.1.2

参见 when 表达式

使用区间(range)

使用 in 运算符来检测某个数字是否在指定区间内:

val x = 10
val y = 9
if (x in 1..y+1) {
    println("fits in range")
}
fits in range
Target platform: JVM Running on kotlin v. 1.1.2

检测某个数字是否在指定区间外:

val list = listOf("a", "b", "c")
if (-1 !in 0..list.lastIndex) {
    println("-1 is out of range")
}
if (list.size !in list.indices) {
    println("list size is out of valid list indices range too")
}
-1 is out of rangelist size is out of valid list indices range too
Target platform: JVM Running on kotlin v. 1.1.2

区间迭代:

for (x in 1..5) {
    print(x)
}
12345
Target platform: JVM Running on kotlin v. 1.1.2

或数列迭代:

for (x in 1..10 step 2) {
    print(x)
}
for (x in 9 downTo 0 step 3) {
    print(x)
}
135799630
Target platform: JVM Running on kotlin v. 1.1.2

参见区间

使用集合

对集合进行迭代:

for (item in items) {
    println(item)
}
applebananakiwi
Target platform: JVM Running on kotlin v. 1.1.2

使用 in 运算符来判断集合内是否包含某实例:

when {
    "orange" in items -> println("juicy")
    "apple" in items -> println("apple is fine too")
}
apple is fine too
Target platform: JVM Running on kotlin v. 1.1.2

使用 lambda 表达式来过滤(filter)和映射(map)集合:

fruits
.filter { it.startsWith("a") }
.sortedBy { it }
.map { it.toUpperCase() }
.forEach { println(it) }
Target platform: JVM Running on kotlin v. 1.1.2

参见高阶函数及Lambda表达式

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值