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

Svetlana Isakova

November 01, 2017
Tweet

More Decks by Svetlana Isakova

Other Decks in Programming

Transcript

  1. 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 ✗
  2. val length = if (s != null) s.length else null

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

    val s: String? Nullability operators val length = s?.length ?: 0
  4. class Optional<T>(val value: T) { 
 fun isPresent() = value

    != null
 
 fun get() = value ?:
 throw NoSuchElementException("No value present") } Nullable types ≠ Optional
  5. Late initialization class KotlinActivity: Activity() { 
 var myData: MyData?

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


    override fun onCreate(savedInstanceState: Bundle?) {
 super.onCreate(savedInstanceState)
 
 myData = intent.getParcelableExtra("MY_DATA")
 } } ... myData .foo ... Late initialization
  7. 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 ...
  8. 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() }
  9. Safe cast val s: String? = any as? String returns

    null if expression cannot be cast val s = if (a is String) a else null