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

Talk about "Nothing"

Kelvin Ko
January 25, 2020

Talk about "Nothing"

Talk about "Nothing" in Kotlin愛好会 x GDG Kyushu
https://gdg.connpass.com/event/160628/

Kelvin Ko

January 25, 2020
Tweet

More Decks by Kelvin Ko

Other Decks in Programming

Transcript

  1. What is “Nothing”? • “A value that never exist”, sounds

    easy to understand • But • What is the different between Null and Nothing? “ଘࡏ͠ͳ͍஋”
  2. Kotlin type system • Nothing is a “Bottom Type” •

    SubType of any other Types (extends all other types) • In opposite, Any is Super class of any other class (World without Null) (World with Null) Image Reference: https://medium.com/@m.sandovalcalvo/kotlin-type-system-unveiling-the-mystery-50613f0db893
  3. So, “Nothing” is • Used as a Type, no instance

    • Bottom Type (Sub Type of any other Type)
  4. Example of Function that never return • listenIncomingConnection will run

    forever (May not be a good way to implement like this, just simple example)
  5. Use case • Adding Nothing, IDE will know the println

    is unreachable This look correct, but actually this line will never run (Video example is uploaded here: https://youtu.be/fjECMd1H-hI)
  6. Use case 2: Exception • After throw Exception, program will

    end • It is more accurate to use “Nothing” as return type to indicate it never return Assume we would Load some data from Database, and throw Exception if it return null (Video example is uploaded here: https://youtu.be/HG210SN4_iI)
  7. • So IDE will warn you the code after TODO

    is unreachable Stdlib’s TODO() • Actually TODO() is implemented like this
  8. Why we need a class that is Sub Type of

    any other classes? Bottom Type Image Reference: https://medium.com/@m.sandovalcalvo/kotlin-type-system-unveiling-the-mystery-50613f0db893
  9. 2. Usage in Generic • Example: A Linked List implementation

    LinkedList Example Reference: https://www.codementor.io/@kotlin_academy/kotlin-s-nothing-its-usefulness-in-generics-j4wcu5taa
  10. Linked List implementation • To represent Empty List, add a

    single instance object • Won’t compile • Kotlin Object cannot have type parameters.
  11. Linked List implementation • How about remove Type parameter ?

    • Won’t compile • The reference to T is unresolved. We must specific a type for T
  12. Linked List implementation • Use “Nothing” as Type • It

    work because Nothing is subtype of any other Type
  13. Conclusion • Nothing is • Subtype of any other type

    (Bottom Type) • Useful in Generic • Indicate function that Never return • Infinite loop • Throw exception