直接上實例:java
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的結果,這個是要出大問題的。app
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異常ui
因此,必定不要爲了保證代碼運行得沒有問題,而濫用 ? 。這樣的作法是錯誤的。this
工程實例:spa
@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異常,代碼運行的是沒有問題的。可是,數據呢?並無保存到數據庫中。code
再次強調,千萬不要濫用Kotlin ?的空檢查。blog