IF表达式
这个没什么好说的,java怎么用,kotlin怎么用,一模一样。但是kotlin的表达式更强大:
java
//三元表达式
String s = "".equals("")? "a":"b";
kotlin
//kotlin类似三元表达式的写法
val s:String = if("".equals("")) "a" else "b"
val max = if(a>b)
{
print("max is a")
a
}else{
print("max is b")
b
}
使用区间
java
public static void main(String[] args){
int x=5,y=9;
if(x >=1 && x <=8){
System.out.println("x 在区间内");
}
}
Kotlin
fun main((args:Array<String>){
val x =5
val y =9
if(x in 1..8){
println("x 在区间内")
}
}
When表达式
when 将它的参数和所有的分支条件顺序比较,直到某个分支满足条件。
when 既可以被当做表达式使用也可以被当做语句使用。如果它被当做表达式,符合条件的分支的值就是整个表达式的值,如果当做语句使用, 则忽略个别分支的值。
when 类似其他语言的 switch 操作符
java
public static void main(String[] args){
int x = 10;
switch(x){
case 1:
System.out.println("1");
break;
case 2:
System.out.println("2");
break;
default:
System.out.println("default");
break;
}
//合并多分枝
switch(x){
case 1:
case 2:
System.out.println("1 or 2");
break;
default:
System.out.println("default");
break;
}
//检测是不是一个特定类型
if(x instanceOf Integer){
System.out.println("x is int");
}else if(x instanceOf Long){
System.out.println("x is long");
}else if(x instanceOf Float){
System.out.println("x is float");
}
}
kotlin
//when语句要比switch强大的多的多
fun main(args:Array<String>){
//类似switch
when(x){
1->println("1")
2->println("2")
else->{
println("else")
}
}
//合并多分枝
when(x){)}{
1,2->println("1 or 2")
else->{
println("else")
}
}
//检测一个值在不在一个区间或集合中
when(x){
in 1..10 -> println("x is in the range")
in validNumbers -> println("x is valid")
!in 10..20 -> println("x is outside the range")
else -> println("else")
}
//检测是不是一个特定的类型
fun hasPrefix(x:Any):Boolean = when(x){
is String -> x.startsWith("prefix")
else -> false
}
//when 也可以用来取代 if-else if链
when{
x.isOdd()-> println("x is odd")
x.isEven()-> println("x is even")
else -> println("x is funny")
}
}