【Kotlin】基础语法学习

时间:2022-05-23 16:49:37

Kotlin简介

Kotlin 是一个基于 JVM 的新的编程语言,由 JetBrains 开发。Kotlin可以编译成Java字节码,也可以编译成JavaScript,方便在没有JVM的设备上运行。JetBrains,作为目前广受欢迎的Java IDE IntelliJ 的提供商,在 Apache 许可下已经开源其Kotlin 编程语言。Kotlin已正式成为Android官方开发语言。

设计目标

1.创建一种兼容Java的语言

2.让它比Java更安全,能够静态检测常见的陷阱。如:引用空指针

3.让它比Java更简洁,通过支持variable type inference,higher-order functions (closures),extension functions,mixins and first-class delegation等实现。

4.让它比最成熟的竞争对手Scala语言更加简单。

基础语法

安装jdk,下载JetBrains开发的IDE:IntelliJ IDEA,就可以新建Kotlin工程,运行Kotlin代码。这里我使用目前最新版IntelliJ IDEA 2017.1.3 x64和JDK 1.8.0作为基础环境。

1. 定义函数

(1)定义一个带有两个Int类型参数,并且返回Int值的函数
fun sum(a: Int, b: Int): Int {
return a + b
}

fun main(args: Array<String>) {
print("3 and 5 is ")
println(sum(3, 5))
}

运行结果:3 and 5 is 8

(2)使用表达式主体和推断返回类型的函数
fun sum(a: Int, b: Int) = a + b

fun main(args: Array<String>) {
print("3 and 5 is ")
println(sum(3, 5))
}

运行结果:3 and 5 is 8

(3)函数返回没有有意义的值
fun printSum(a: Int, b: Int): Unit {
println("sum of $a and $b is ${a + b}")
}

fun main(args: Array<String>) {
printSum(-1, 8)
}

运行结果:sum of -1 and 8 is 7

在IDE中查看Unit类型源码,可以看到注释说这种类型对应Java中的void类型,也就是空

package kotlin

/**
* The type with only one value: the Unit object. This type corresponds to the `void` type in Java.
*/

public object Unit {
override fun toString() = "kotlin.Unit"
}
(4)Unit 在函数返回类型中可以省略
fun printSum(a: Int, b: Int) {
println("sum of $a and $b is ${a + b}")
}

fun main(args: Array<String>) {
printSum(-1, 8)
}

运行结果:sum of -1 and 8 is 7

2. 定义局部变量

(1)局部变量只赋值一次的(只读)
fun main(args: Array<String>) {
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
println("a = $a, b = $b, c = $c")
}

运行结果:a = 1, b = 2, c = 3

如果强行再次给a、b、c其中之一赋值,例如我给a再次赋值5,IDE中就会直接报错a = 5这行,尝试运行就会得到报错信息:Error:(9, 5) Kotlin: Val cannot be reassigned

fun main(args: Array<String>) {
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
a = 5
println("a = $a, b = $b, c = $c")
}
(2)可变变量
fun main(args: Array<String>) {
var s = 5 // `Int` type is inferred
s += 1
println("x = $s")
}

运行结果:x = 6

3.注释

就像Java和JavaScript,Kotlin支持//和/**/注释。不像Java,Kotlin可以在/**/注释中和嵌套注释块。

// This is an end-of-line comment

/* This is a block comment
on multiple lines. */

Java中嵌套注释块,报错

public class Main {

public static void main(String[] args) {
/*/*vhfgh*/
System.out.println("Hello World!");*/
}
}

Error:(5, 44) java: 非法的表达式开始

Error:(5, 45) java: 非法的表达式开始

Error:(6, 5) java: 非法的表达式开始

Error:(7, 2) java: 解析时已到达文件结尾

Kotlin中嵌套注释块正常

fun main(args: Array<String>) {
var s = 5 // `Int` type is inferred
/*s += 1
/*hahha*/

println("x = $s")*/
}

4.使用字符串模板

fun main(args: Array<String>) {
var a = 5
// simple name in template(模板中使用简单名字):
val s1 = "a is $a"
println(s1)
a = 100
// arbitrary expression in template(模板中使用任意表达式):
val s2 = "${s1.replace("is", "was")}, but now is $a"
println(s2)
}

运行结果:

a is 5

a was 5, but now is 100

5.使用条件表达式

以下的普通maxOf函数和使用if表达式的maxVal函数是等价的

fun maxOf(a: Int, b: Int): Int {
if (a > b) {
return a
} else {
return b
}
}

/**
* 使用if表达式
*/

fun maxVal(a: Int, b : Int) = if (a > b) a else b

fun main(args: Array<String>) {
println("max of 0 and 42 is ${maxOf(0, 42)}")
println("max of 0 and 42 is ${maxVal(0, 42)}")
}

运行结果:

max of 0 and 42 is 42

max of 0 and 42 is 42

6.使用可空值和检查空值

当null值是可能的,引用时必须显式地标记为可为空。

返回null,如果str不持有一个整数

fun parseInt(str: String): Int? {
// ...
}
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("either '$arg1' or '$arg2' is not a number")
}
}


fun main(args: Array<String>) {
printProduct("6", "7")
printProduct("a", "7")
printProduct("a", "b")
}

运行结果:

42

either ‘a’ or ‘7’ is not a number

either ‘a’ or ‘b’ is not a number

或者可以这样写

fun parseInt(str: String): Int? {
return str.toIntOrNull()
}

fun printProduct(arg1: String, arg2: String) {
val x = parseInt(arg1)
val y = parseInt(arg2)

// ...
if (x == null) {
println("Wrong number format in arg1: '${arg1}'")
return
}
if (y == null) {
println("Wrong number format in arg2: '${arg2}'")
return
}

// x and y are automatically cast to non-nullable after null check
println(x * y)
}

fun main(args: Array<String>) {
printProduct("6", "7")
printProduct("a", "7")
printProduct("99", "b")
}

运行结果:

42

Wrong number format in arg1: ‘a’

Wrong number format in arg2: ‘b’

7.使用类型检查和自动转换

这是操作符检查,是否表达式是类型的实例。如果一个不可变的局部变量或属性为特定类型检查,没有必要把它显式转换。

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 main(args: Array<String>) {
fun printLength(obj: Any) {
println("'$obj' string length is ${getStringLength(obj) ?: "... err, not a string"} ")
}
printLength("Incomprehensibilities")
printLength(1000)
printLength(listOf(Any()))
}

运行结果:

‘Incomprehensibilities’ string length is 21

‘1000’ string length is … err, not a string

‘[java.lang.Object@2626b418]’ string length is … err, not a string

或者这样写

fun getStringLength(obj: Any): Int? {
if (obj !is String) return null

// `obj` is automatically cast to `String` in this branch
return obj.length
}


fun main(args: Array<String>) {
fun printLength(obj: Any) {
println("'$obj' string length is ${getStringLength(obj) ?: "... err, not a string"} ")
}
printLength("Incomprehensibilities")
printLength(1000)
printLength(listOf(Any()))
}

还可以这样写

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
}


fun main(args: Array<String>) {
fun printLength(obj: Any) {
println("'$obj' string length is ${getStringLength(obj) ?: "... err, is empty or not a string at all"} ")
}
printLength("Incomprehensibilities")
printLength("")
printLength(1000)
}

8.使用for循环

使用for循环,这和python、groovy语法非常相似

fun main(args: Array<String>) {
val items = listOf("apple", "banana", "kiwi")
for (item in items) {
println(item)
}
}

运行结果:

apple

banana

kiwi

fun main(args: Array<String>) {
val items = listOf("apple", "banana", "kiwi")
for (index in items.indices) {
println("item at $index is ${items[index]}")
}
}

运行结果:

item at 0 is apple

item at 1 is banana

item at 2 is kiwi

9.使用while循环

fun main(args: Array<String>) {
val items = listOf("apple", "banana", "kiwi")
var index = 0
while (index < items.size) {
println("item at $index is ${items[index]}")
index++
}
}

运行结果:

item at 0 is apple

item at 1 is banana

item at 2 is kiwi

10.使用when表达式

fun describe(obj: Any): String =
when (obj) {
1 -> "One"
"Hello" -> "Greeting"
is Long -> "Long"
!is String -> "Not a string"
else -> "Unknown"
}

fun main(args: Array<String>) {
println(describe(1))
println(describe("Hello"))
println(describe(1000L))
println(describe(2))
println(describe("other"))
}

运行结果:

One

Greeting

Long

Not a string

Unknown

11.使用范围

使用in操作符检查数字是否在范围内

fun main(args: Array<String>) {
val x = 10
val y = 9
if (x in 1..y+1) {
println("fits in range")
}
}

运行结果:fits in range

注意边界,是包含最大值的,这里的范围1..y+1,代表[1,10]包含左右边界,使用in操作符测试1~10的数字都是在范围内的

检查数字不在范围内

fun main(args: Array<String>) {
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 range

list size is out of valid list indices range too

迭代一个范围

fun main(args: Array<String>) {
for (x in 1..5) {
print(x)
}
}

运行结果:12345

使用步长迭代一个范围,还可以使用downTo从大到小

fun main(args: Array<String>) {
for (x in 1..10 step 2) {
print(x)
}
print(" ")
for (x in 9 downTo 0 step 3) {
print(x)
}
}

运行结果:13579 9630

12.使用集合

迭代集合,和迭代范围一样

fun main(args: Array<String>) {
val items = listOf("apple", "banana", "kiwi")
for (item in items) {
println(item)
}
}

运行结果:

apple

banana

kiwi

使用in操作符检查集合是否包含对象

fun main(args: Array<String>) {
val items = setOf("apple", "banana", "kiwi")
when {
"orange" in items -> println("juicy")
"apple" in items -> println("apple is fine too")
}
}

运行结果:apple is fine too

使用lambda表达式过滤和映射集合,而且有点流式编程的意思

fun main(args: Array<String>) {
val fruits = listOf("banana", "avocado", "apple", "kiwi")
fruits.filter { it.startsWith("a") }
.sortedBy { it }
.map { it.toUpperCase() }
.forEach { println(it) }
}

运行结果:

APPLE

AVOCADO

13.定义包

包定义应该在源文件的最顶部。它不需要匹配目录和包:源文件可以放在任意的文件系统。

package my.demo

import java.util.*

// ...