请问这个函数能简化吗?


#1
fun <T : Any> readConfig(name: String, default: T): T {
    val db = writableDatabase
    var rv = ""

    val cursor =
        db.query(tConfig, arrayOf("value"), "name=?", arrayOf(name), null, null, null, null)
    if (cursor.moveToFirst()) {
        rv = cursor.getString(cursor.getColumnIndex("value"))
    } else {
        cursor.close()
        return default
    }
    cursor.close()

    when (default) {
        is Byte -> {
            return try {
                rv.toByte() as T
            } catch (e: Exception) {
                default
            }
        }
        is Short -> {
            return try {
                rv.toShort() as T
            } catch (e: Exception) {
                default
            }
        }
        is Int -> {
            return try {
                rv.toInt() as T
            } catch (e: Exception) {
                default
            }
        }
        is Long -> {
            return try {
                rv.toLong() as T
            } catch (e: Exception) {
                default
            }
        }
        is Float -> {
            return try {
                rv.toFloat() as T
            } catch (e: Exception) {
                default
            }
        }
        is Double -> {
            return try {
                rv.toDouble() as T
            } catch (e: Exception) {
                default
            }
        }
        is Boolean -> {
            return try {
                rv.toBoolean() as T
            } catch (e: Exception) {
                default
            }
        }
        is String -> {
            rv as T
        }
    }

    return default
}

}


#2

https://github.com/Vove7/SmartKey 个人开发有关Config库 欢迎提出想法建议


#3

<T:Any>可见简化为<T>,任何类型都是any的子类


#4

Any? 不是 Any 的子类


#5

太神奇了


#6

语法上可以这么写


#7

非常感谢!


#8

既然已经判断了类型再做转化了,那么这个try还有存在的必要么,感觉应该不需要try了吧


#9

感觉可以用contract


#10

rv 的内容是从数据库读出,不一定能成功转换。


#11

可否详细一点呢?


#13


这样是不是更简洁?


#14

一下子还看不懂,但肯定你是高人!


京ICP备16022265号-2 Kotlin China 2017 - 2018