- Learn Kotlin Programming(Second Edition)
- Stephen Samuel Stefan Bocutiu
- 104字
- 2021-06-24 14:13:36
Extension functions on null values
Kotlin even supports extension functions on null values. In those situations, the this reference will contain the null value, and so, Any function that doesn't safely handle null references would throw a null pointer exception.
This functionality is how the equals function can be overloaded to provide safe usage to even null values:
fun Any?.safeEquals(other: Any?): Boolean { if (this == null && other == null) return true if (this == null) return false return this.equals(other) }
This function can be called from both null and non-null values, and the Kotlin compiler will handle both cases for you.
推薦閱讀
- Mastering Concurrency Programming with Java 8
- 深度實踐OpenStack:基于Python的OpenStack組件開發
- Java Web基礎與實例教程(第2版·微課版)
- 編程卓越之道(卷3):軟件工程化
- INSTANT Sencha Touch
- OpenNI Cookbook
- Backbone.js Blueprints
- 單片機應用與調試項目教程(C語言版)
- Python時間序列預測
- Mastering Drupal 8 Views
- Hands-On GUI Programming with C++ and Qt5
- Spring+Spring MVC+MyBatis從零開始學
- Getting Started with Python and Raspberry Pi
- 區塊鏈項目開發指南
- Managing Microsoft Hybrid Clouds