110

Basic Kotlin cheatsheet - outlined in Checkvist

 6 years ago
source link: https://checkvist.com/checklists/643867-basic-kotlin-cheatsheet
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

Basic Kotlin cheatsheet / read-only

  • 💡 Use filter / on top of the page to look for a particular topic

  • Unsorted Basics

    • val positives = list.filter { it > 0 }
      
      for ((k, v) in map) {
          println("$k -> $v")
      }
      
      val list = listOf("a", "b", "c") // read-only list
      val map = mapOf("a" to 1, "b" to 2, "c" to 3) // read-only map
      
      // Lazy property
      val p: String by lazy {  
          // compute the string
      }
      
      // Singleton
      object Resource {
          val name = "Name"
      }
      
    • String templates

    • Multiline

    • var a: String = "abc"
      a = null // compilation error
      
      var b: String? = "abc"
      b = null // ok
      
      b?.length // call length if b is not null, return null otherwise
      
      val l = b!!.length // If you really want NPE
      
      val l = b?.length ?: -1  // l = -1 if b is null, or b.length otherwise
      
      fun foo(node: Node): String? {
          val parent = node.getParent() ?: return null
          val name = node.getName() ?: throw IllegalArgumentException("name expected")
          // ...
      }
      
      val aInt: Int? = a as? Int  // Safe type cast
      
    • WHILE

    • Unit = analog of void, can be omitted for return value of a function

    • Default parameters

    • Variable parameters

    • Simplest form, like daemon thread

    • Timeout

    • Cancellable job

    • Async execution of 2 functions


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK