简书链接:kotlin函数的举例
文章字数:51,阅读全文大约需要1分钟

1
fun theAnswer() = 42

实际上等于

1
2
3
fun theAnswer ():Int{
return 42;
}

类似java的switch逻辑分支函数

1
2
3
4
5
6
fun transform(color: String): Int = when (color) {
"Red" -> 0
"Green" -> 1
"Blue" -> 2
else -> throw IllegalArgumentException("Invalid color param value")
}

等于

1
2
3
4
5
6
7
fun transform(color: String): Int {
return when (color) {
"Red" -> 0
"Green" -> 1
"Blue" -> 2
else -> throw IllegalArgumentException("Invalid color param value")
}

如果用java表达 那么是

1
2
3
4
5
6
7
8
9
10
11
12
13
public int transform(String color){
switch(color){
case "Red"
return 0;
case "Green";
return 1;
case "Blue":
return 2;
default:
throw new IllegalArgumentException("Invalid color param value");
}
}