一.导包与包的声明
包的声明:(包的声明应处于源文件顶部)
package my.demo
导包:
import java.util.*
总结:
Kotlin导包和包的声明与Java基本上相同(Sacla使用下划线指代多个,还可以指定多个,使用{}和,配合使用)
二.函数的定义(主要是和Scala作比较)
1.一般结构
Kotlin版本:
fun sum(a: Int, b: Int): Int {
return a + b
}
Scala版本:
def sum(a: Int, b: Int): Int = {
a+b
}
总结:
1) 关键字不同
2)返回值后面Kotlin没有等号,而Scala有
3)Kotlin沿用Java的返回值关键字return,scala则不需要关键字
2.表达式作为函数体、返回值类型自动推断的函数
Kotlin版本:
fun sum(a: Int, b: Int) = a + b
Scala版本:
def sum(a: Int, b: Int) = a + b
总结:
除了关键字不同,基本一样
3.函数返回无意义的值
Kotlin版本:
fun printSum(a: Int, b: Int): Unit {
println("sum of $a and $b is ${a + b}")
}
Scala版本:
def printSum(a: Int, b: Int): Unit = {
println(f"sum of $a and $b is ${a + b}")
}
总结:
= 和在解析字符串中变量的引用时不同(Scala需要前面多加一个f)
三.常量和变量的定义
val a: Int = 1 // 立即赋值
val b = 2 // 自动推断出 `Int` 类型
val c: Int // 如果没有初始值类型不能省略
c = 3 // 明确赋值
var x = 5 // 自动推断出 `Int` 类型
x += 1
同Scala一样,有自动类型推断,不同于JS的泛类型,变量的值是不能够随时改变的。
四.Kotlin注释
单行注释 //
多行注释 /* 内容 */
五.字符串模板
var a = 1
// 模板中的简单名称:
val s1 = "a is $a"
a = 2
// 模板中的任意表达式:
val s2 = "${s1.replace("is", "was")}, but now is $a"
总结:
和Scala中类似,只是不需要再前面加上f啥的,相比较于C语言中的printf更加方便
六.使用条件表达式
fun maxOf(a: Int, b: Int): Int {
if (a > b) {
return a
} else {
return b
}
}
fun maxOf(a: Int, b: Int) = if (a > b) a else b
总结:
基本上与Scala语法一样
七.使用可空值及 null 检测
当某个变量的值可以为 null 的时候,必须在声明处的类型后添加
?
来标识该引用可为空.
在Scala中,遇到此情况通常是返回一个Option类型的值。
使用返回可空值的函数:
parseInt(a) 当不能够转换为整型后会返回null,这点相对于Scala方便多了
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")
}
}
八.使用类型检测及自动类型转换
is 运算符检测一个表达式是否某类型的一个实例。
如果一个不可变的局部变量或属性已经判断出为某类型,那么检测后的分支中可以直接当作该类型使用,无需显式转换
fun getStringLength(obj: Any): Int? {
if (obj !is String) return null
// `obj` 在这一分支自动转换为 `String`
return obj.length
}
或者:
fun getStringLength2(obj: Any): Int? {
// `obj` 在 `&&` 右边自动转换成 `String` 类型
if (obj is String && obj.length > 0) {
return obj.length
}
return null
}
在scala中不支持,需要利用isInstanceOf配合asInstanceOf或者使用模式匹配进行转换后再操作
九.使用循环
1.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]}")
}
在Scala中:
val items = List("apple", "banana", "kiwifruit")
for (item <- items) {
println(item)
}
或者:
val items = List("apple", "banana", "kiwifruit")
for (index <- items.indices) {
println(items.slice(index,index+1).productElement(0))
}
上面的情况在scala中一般使用map配合foreach即通过lambda表达式形式实现,没有熟好熟劣
2.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"
}
有点类似scala的模式匹配
十一.使用区间(range)
使用 in 运算符来检测某个数字是否在指定区间内
val x = 10
val y = 9
if (x in 1..y+1) {
println("fits in range")
}
Scala中还是模式匹配
检测某个数字是否在指定区间外:
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)
}
十二.使用集合
1.对集合进行迭代:
for (item in items) {
println(item)
}
2.使用 in 运算符来判断集合内是否包含某实例:
when {
"orange" in items -> println("juicy")
"apple" in items -> println("apple is fine too")
}
3.使用 lambda 表达式来过滤(filter)与映射(map)集合:
val fruits = listOf("banana", "avocado", "apple", "kiwifruit")
fruits
.filter { it.startsWith("a") }
.sortedBy { it }
.map { it.toUpperCase() }
.forEach { println(it) }
Scala的翻版