Kotlin与Java基本语法对比(四)

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")
    
    }
    
    
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值