Android kotlin如何在没有break语句的情况下拥有切换条件

时间:2018-02-11 06:06:53

标签: java android kotlin

我在Java中有switch没有break语句。当我转变为Kotlin。它已经放置When我测试并执行了我传递给该函数的条件

这是 JAVA

的代码
 switch (version) {
            case 1:
                onCreate(db);

            case 2:
                db.execSQL("CREATE TABLE IF NOT EXISTS ");
                db.execSQL("CREATE TABLE IF NOT EXISTS ");
        }

科特林

 when (version) {
                1 -> {
                    onCreate(db)
                }

                2 -> {
                    db.execSQL("CREATE TABLE IF NOT EXISTS ")
                    db.execSQL("CREATE TABLE IF NOT EXISTS ")
                }
            }

2 个答案:

答案 0 :(得分:4)

怎么样:

if (version <= 1) {
    onCreate(db)
}

if (version <= 2) {
    db.execSQL("CREATE TABLE IF NOT EXISTS ")
    db.execSQL("CREATE TABLE IF NOT EXISTS ")
}

答案 1 :(得分:0)

您可以随时使用kotlin here中的范围自定义时间

     when {
            version in 0..1  -> {
                onCreate(db)
            }
            version in 1..2 -> {
                //do something else
                onCreate(db)
                dbExe(db)
            }
            else ->{
               //handle unexpected here    
            }
        }

fun onCreate(val db: SQLiteOpenHelper){
  //oncreate goes here
}

fun dbExe(val db: SQLiteOpenHelper){
  // execute sql statement goes here
     db.execSQL("CREATE TABLE IF NOT EXISTS ")
     db.execSQL("CREATE TABLE IF NOT EXISTS ")
}