请不要乱用Kotlin ? 空检查

直接上实例:

fun main(args: Array<String>) {
    println("now, begin save data to database")
    val dataBaseOperator: DataBaseOperator? = null
    dataBaseOperator?.saveDataToDataBase("important things")
    println("""return "ok" to other services""")
}

class DataBaseOperator {

    fun saveDataToDataBase(data: String) {
        println("save data $data to database")
    }
}

代码运行得完全没有问题,输出结果:

now, begin save data to database
return "ok" to other services

But,很明显,我们的数据并没有保存到数据库中,但返回给了其他服务OK的结果,这个是要出大问题的。

fun main(args: Array<String>) {
    println("now, begin save data to database")
    val dataBaseOperator: DataBaseOperator? = null
    // 错误做法
    //dataBaseOperator?.saveDataToDataBase("important things")
    // 正确做法
    dataBaseOperator!!.saveDataToDataBase("important things")
    println("""return "ok" to other services""")
}

正确的做法是直接抛出异常。因为数据库没有保存到数据库中,原因是null异常

所以,一定不要为了保证代码运行得没有问题,而滥用 ? 。这样的做法是错误的。

 

工程实例:

@Controller
class OrderController {

    val logger = LoggerFactory.getLogger(this.javaClass)

    @Autowired
    var orderService: PayOrderService? = null

    @PostMapping("payAliPay")
    @ResponseBody
    fun payAliPay(@RequestParam(value = "user_id", required = true) user_id: Long) {
        // 保存数据到数据库中
        orderService?.saveDataToDataBase(user_id)
        println("""return "ok" to other services""")
    }

}

因为在Spring Boot中,有需要是自动导入的实例,如果这时候,我们使用?来规避抛出null异常,代码运行的是没有问题的。但是,数据呢?并没有保存到数据库中。

再次强调,千万不要滥用Kotlin ?的空检查。

 

posted @ 2018-06-01 14:55  H_bolin  阅读(1008)  评论(0编辑  收藏  举报