Upgrade to Pro — share decks privately, control downloads, hide ads and more …

2. Nullable Types in Kotlin [kotlin-workshop]

2. Nullable Types in Kotlin [kotlin-workshop]

Part of https://github.com/jetBrains/kotlin-workshop.

Covers:
- Nullable types
- Late Initialization
- Type Casts

C6997ce411091d4a51ea3caa2109c0b0?s=128

Svetlana Isakova

November 01, 2017
Tweet

Transcript

  1. Nullability

  2. Billion Dollar Mistake

  3. Modern approach: to make NPE compile-time error, not run-time error

  4. Nullable types in Kotlin val s1: String = "always not

    null" 
 val s2: String? = null s1.length ✓ ✗ s2.length "can be null or non-null" null ✗
  5. val s: String? if (s != null) {
 s.length
 }

    Dealing with Nullable Types
  6. s?.length val s: String? Dealing with Nullable Types

  7. val length = if (s != null) s.length else null

    val s: String? Nullability operators val length: Int? = s?.length
  8. val length = if (s != null) s.length else 0

    val s: String? Nullability operators val length = s?.length ?: 0
  9. val s: String? if (s == null) fail()
 s.length Control-flow

    analysis
  10. val s: String? Making NPE explicit s!! throws NPE if

    s is null s!!.length
  11. Nullable Types Under the Hood No performance overhead @Nullable, @NotNull

    annotations
  12. class Optional<T>(val value: T) { 
 fun isPresent() = value

    != null
 
 fun get() = value ?:
 throw NoSuchElementException("No value present") } Nullable types ≠ Optional
  13. lateinit

  14. Late initialization class KotlinActivity: Activity() { 
 var myData: MyData?

    = null
 
 override fun onCreate(savedInstanceState: Bundle?) {
 super.onCreate(savedInstanceState)
 
 myData = intent.getParcelableExtra("MY_DATA")
 } 
 } ... myData ?.foo ...
  15. class KotlinActivity: Activity() { 
 lateinit var myData: MyData 


    override fun onCreate(savedInstanceState: Bundle?) {
 super.onCreate(savedInstanceState)
 
 myData = intent.getParcelableExtra("MY_DATA")
 } } ... myData .foo ... Late initialization
  16. If the property wasn’t initialized kotlin.UninitializedPropertyAccessException: lateinit property myData has

    not been initialized Still runtime exception, but with the detailed message ... myData .foo ...
  17. Type casts

  18. Type casts: as, as? if (any is String) { val

    s = any as String s.toUpperCase() } not necessary = instanceof smart cast if (any is String) { any.toUpperCase() }
  19. Safe cast val s: String? = any as? String returns

    null if expression cannot be cast val s = if (a is String) a else null
  20. Copyright © 2017 https://github.com/JetBrains/kotlin-workshop