-
常量和变量
-
常量
Java
static final int b = 1;
Kotlin
// 全局范围内,只能修饰基本类型和String,必须立即初始化 const val b = 3
-
变量
Java
int a = 10;
Kotlin
var a = 1
-
只读变量
Java
final int b = 1;
Kotlin
// 为局部变量时,与Java等价 val b = 1 // 作为属性时,值可变,不能写只能读 class Params { private var varP = 1 private val b = 1 val valP: Int get() { return varP } }
-
-
分支表达式(Java是语句,Kotlin是表达式)
-
if...else
Java
int a = 0; int c = a == 3 ? 4 : 5;
Kotlin
val a = 0 val c = if (a == 3) 4 else 5
-
when
Java
int a = 0; int c = 0; switch (a) { case 0: c = 5; break; case 1: c = 100; break; default: c = 20; }
Kotlin
val a = 0 val c = when (a) { 0 -> 5 1 -> 100 else -> 20 } val x: Any = "" // 条件转移到分支, val c = when { // 智能类型转换 x is String -> x.length x == 1 -> 100 else -> throw Exception() } // 可赋值 val a = when (val input = readLine()) { null -> 0 else -> input.length }
-
try...catch
Java
int a = 0, b = 0, c = 0; try { c = a / b; } catch (Exception e) { e.printStackTrace(); c = 0; }
Kotlin
val a = 0 val b = 0 var c = 0 c = try { a / b } catch (e: Exception) { e.printStackTrace() 0 }
-
-
运算符与中缀表达式
-
运算符
val a = 0 val b = 0 var c = 0 // / 与 div c = a / b c = a.div(b)
-
运算符重载
运算符重载需要使用
operator
关键字,示例运算符是+
,函数名是plus
,// Complex.kt class Complex(var real: Int, var image: Int) { override fun toString(): String { return "$real + ${image}i" } } operator fun Complex.plus(other: Complex): Complex = Complex(this.real + other.real, this.image + other.image) // Test.kt val complex = Complex(1, 2) println(complex + complex) // 输出:2 + 4i
-
中缀表达式
需要使用
infix
关键字val mapOf = mapOf(1 to "one", 2 to "two", 3.to("three")) // 具体实现 public infix fun <A, B> A.to(that: B): Pair<A, B> = Pair(this, that)
-
-
Lambda 表达式
本质是实现有单一抽象方法的接口的匿名类,匿名类执行方法。