Kotlin基础语法
2021-02-24 本文已影响0人
candice2cc
package定义与import
package my.demo
import kotlin.text.*
// ...
程序入口
fun main() {
println("Hello world!")
}
另一种接受可变数量String参数的main
fun main(args: Array<String>) {
println(args.contentToString())
}
打印标准输出
print("Hello ")
print("world!")
println("Hello world!")
println(42)
函数
fun sum(a: Int, b: Int): Int {
return a + b
}
函数体可以是表达式
fun sum(a: Int, b: Int) = a + b
无意义返回值
fun printSum(a: Int, b: Int): Unit {
println("sum of $a and $b is ${a + b}")
}
Unit返回类型可以省略
变量
val:定义常量
val a: Int = 1 // immediate assignment
val b = 2 // `Int` type is inferred
val c: Int // Type required when no initializer is provided
c = 3 // deferred assignment
var:定义变量
var x = 5 // `Int` type is inferred
x += 1
可以在顶层定义变量
val PI = 3.14
var x = 0
fun incrementX() {
x += 1
}
创建类Class和实例instances
class Shape
class Rectangle(var height: Double, var length: Double) {
var perimeter = (height + length) * 2
}
类构造函数里面的变量默认可用
val rectangle = Rectangle(5.0, 2.0)
println("The perimeter is ${rectangle.perimeter}")
类之间继承使用:
,一个类可继承,标记为open
open class Shape
class Rectangle(var height: Double, var length: Double): Shape {
var perimeter = (height + length) * 2
}
注释
// This is an end-of-line comment
/* This is a block comment
on multiple lines. */
块注释可以内嵌
/* The comment starts here
/* contains a nested comment */
and ends here. */
字符串模板
var a = 1
// simple name in template:
val s1 = "a is $a"
a = 2
// arbitrary expression in template:
val s2 = "${s1.replace("is", "was")}, but now is $a"
条件表达式
fun maxOf(a: Int, b: Int): Int {
if (a > b) {
return a
} else {
return b
}
}
在kotlin,if还可以当成表达式使用。
fun maxOf(a: Int, b: Int) = if (a > b) a else b
for循环
val items = listOf("apple", "banana", "kiwifruit")
for (item in items) {
println(item)
}
val items = listOf("apple", "banana", "kiwifruit")
for (index in items.indices) {
println("item at $index is ${items[index]}")
}
while循环
val items = listOf("apple", "banana", "kiwifruit")
var index = 0
while (index < items.size) {
println("item at $index is ${items[index]}")
index++
}
when表达式
fun describe(obj: Any): String =
when (obj) {
1 -> "One"
"Hello" -> "Greeting"
is Long -> "Long"
!is String -> "Not a string"
else -> "Unknown"
}
Ranges
使用in
判断数值是否位于一个区间范围
val x = 10
val y = 9
if (x in 1..y+1) {
println("fits in range")
}
判断数值是否超出区间
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")
}
区间遍历
for (x in 1..5) {
print(x)
}
阶梯式遍历区间
for (x in 1..10 step 2) {
print(x)
}
println()
for (x in 9 downTo 0 step 3) {
print(x)
}
集合
遍历集合
for (item in items) {
println(item)
}
检查集合中是否包含某个元素使用in
when {
"orange" in items -> println("juicy")
"apple" in items -> println("apple is fine too")
}
使用lambda表达式对集合进行filter和map操作
val fruits = listOf("banana", "avocado", "apple", "kiwifruit")
fruits
.filter { it.startsWith("a") }
.sortedBy { it }
.map { it.toUpperCase() }
.forEach { println(it) }
空值和空值判断
当为null时,必须显示标记为nullable。nullable类型的名称后面带有?
。
如果str无法转换成数字,返回null
fun parseInt(str: String): Int? {
// ...
}
null的函数返回值的范例
fun parseInt(str: String): Int? {
return str.toIntOrNull()
}
fun printProduct(arg1: String, arg2: String) {
val x = parseInt(arg1)
val y = parseInt(arg2)
// Using `x * y` yields error because they may hold nulls.
if (x != null && y != null) {
// x and y are automatically cast to non-nullable after null check
println(x * y)
}
else {
println("'$arg1' or '$arg2' is not a number")
}
}
fun main() {
printProduct("6", "7")
printProduct("a", "7")
printProduct("a", "b")
}
类型检查和自动转换
is
操作符用来检查表达式是否是某个类型实例。如果变量进行过is
类型判断,无需再显示进行转换。
fun getStringLength(obj: Any): Int? {
if (obj is String) {
// `obj` is automatically cast to `String` in this branch
return obj.length
}
// `obj` is still of type `Any` outside of the type-checked branch
return null
}
fun getStringLength(obj: Any): Int? {
if (obj !is String) return null
// `obj` is automatically cast to `String` in this branch
return obj.length
}
fun getStringLength(obj: Any): Int? {
// `obj` is automatically cast to `String` on the right-hand side of `&&`
if (obj is String && obj.length > 0) {
return obj.length
}
return null
}