Kotlin

2019-07-21

> There is no best programming language in the world, just as there is no best person in the world.

There is no best programming language in the world, just as there is no best person in the world.

If you want to know how good or bad a programming language is, go learn it.

I have been using Kotlin for almost a year, but lately it has felt both familiar and unfamiliar, so I could not help revisiting the language.

 

The Most Comfortable Parts of the Language

  1. Nullable types: no more null-check boilerplate
  2. when, a powerful branching construct: the strongest among the languages I know
  3. if, usable as an expression: no need to declare a separate variable
  4. object, singletons at the language level
  5. Closures, very practical

 

Overview

  1. Development tools

    • Intellij IDEA:
    • Sublime Text:
    • Vscode:
  2. Procedural programming

    • Basic syntax and conventions

      • Variables
        • var a = "hello"
      • Constants
        • val a = "name" // runtime constant
        • const val co = "constant" // compile-time constant; can only be used for top-level or object-level constant declarations, and only for String and primitive types
      • Comments
        • // Single-line comment
        • /* Block comment */
        • /* /nested comment/ */
        • File comments
          • Copyright information
          • License information
          • Description
          • Version history
        • Documentation comments: for public SDKs
          • Kdoc
          • @author
          • @deprecated
          • @param
          • @return
          • @version
        • Code comments: for reference when reading source code
        • Landmark comments: an IDE feature
          • //TODO: code not yet finished
          • //FIXME: code is buggy, needs fixing
      • Naming conventions
        • Package names: all lowercase, separated by dots
        • Class and interface names: UpperCamelCase
        • File names: UpperCamelCase
        • Variable names: lowerCamelCase
        • Compile-time constants: all uppercase, underscores allowed
        • Function names: lowerCamelCase
      • Code layout
        • Blank lines
          • After a code comment (except trailing comments)
          • Before the first statement in a function
          • Between two logical sections within a function
          • Between class or interface declarations
        • Spaces
          • Around assignment operators
          • Around binary operators
          • Before and after parentheses
          • Between function arguments
          • Class inheritance and interface implementation
          • Around the braces of lambda expressions
        • Indentation
          • 4 spaces
        • Line breaks
          • After commas and before operators
          • When declaring a class
        • Omissions
          • Semicolons
          • Omitting Unit
          • Lambda parameters
    • Data types

      • Integers
        • Byte
          • 8 bits
          • -128~127
        • Short
          • 16 bits
          • -2 ^ 15 ~ 2 ^ 15 - 1
        • Int
          • 32 bits
          • -2 ^ 31 ~ 2 ^ 31 -1
        • Long
          • 64 bits
          • -2 ^ 63 ~ 2 ^ 63 -1
      • Floating-point numbers
        • Float
          • 32 bits
          • 3.0F
        • Double
          • 64 bits
          • decimal literals default to double
        • Scientific notation
          • 3.14e15
      • Characters
        • Kotlin characters use two-byte Unicode encoding (16 bits)
        • Can be expressed in hexadecimal
          • val a = 'A'
          • val b = '\u0041'
          • val c = '码'
        • Escape characters
          • \t \u0009 Tab
          • \n \u000a Newline
          • \r \u000d Carriage return
          • " \u0022 Double quote
          • ' \u0027 Single quote
          • \ \u005c Backslash
          • $ \u0024 Dollar sign
          • \b \u0008 Backspace
      • Booleans
        • true
        • false
      • Conversions between data types
        • toXXX(): conversion functions
        • ⚠️ Converting from a larger to a smaller type risks precision loss
        • Implicit conversion precedence: double > float > Long > Int
      • Nullable types
        • Prevents null pointer exceptions
        • Null-safety operators
          • Safe call operator ?.
          • as?
          • Elvis operator ?:
          • Not-null assertion !!
          • let
      • Strings
        • Ordinary strings
        • Raw strings
          • Can contain any character but cannot contain escape characters
          • == checks whether two objects have equal content
        • Immutable Strings

        • String operations
          • Concatenation
            • a + b
          • Templates
            • $x
          • Search
            • indexOf: searches forward starting at x
            • lastIndexOf: searches backward starting at x
          • Comparison
            • Equality
            • Ordering
            • Prefixes and suffixes
          • Substring extraction
            • Range extraction: half-open intervals
        • Mutable strings
          • StringBuilder
          • Append
          • Insert
          • Delete
          • Replace
        • Regular expressions
          • Regex
          • String matching

            Regex(""""\d+""").matchs("1233")

          • String search

            Regex(""""\d+""").find("1233")

          • String replacement

            Regex("""\d+""").replace("123mmm", "")

          • String splitting

            Regex("""\d+""").split("123mmm")

    • Operators

      • Arithmetic operators
        • Unary operators
          • Negation: -a
          • Increment: ++
          • Decrement: --
        • Binary operators
          • a + b
          • a - b
          • a * b
          • a / b
          • a % b
        • Arithmetic assignment operators
          • a += 1
          • a -= 1
          • a *= 2
          • a /= 2
          • a %= 2
      • Relational operators
        • == 、>、<、>=、<= 、===、!==
      • Logical operators
        • &&、||
      • Bitwise operators
        • inv 位反
        • and 位与
        • or 位或
        • xor 位异或
        • shr 有符号右移
        • shl 左移
        • ushr 无符号右移
      • Other operators
        • Class A : B()、()、[]、.=、?、?.、?:、!!、::、..、-> 、*
      • Operator precedence (highest to lowest)
        • ()
        • ++ 、-- 、 . 、 ?. 、?
        • -、 + 、 ++ 、-- 、!
        • :、as、as?
        • * 、 / 、%
        • +、-
        • ..
        • 中缀运算符
        • Elvis运算符 ?:
        • in、!in、is、!is
        • <、>、<=、>=
        • ==、!=、===、!==
        • &&
        • ||
        • =、+=、-=、*= 、/= 、%=
    • Control flow

      • if
        • if(true) a = 1
        • val a = if(true) "" else null
      • when
        • when() {}
        • val a = when(name)
      • while {}
      • do {} while
      • for () {}
      • break
        • label@ for (x in 0..8) {
        •  for (y in 0..8) {
        •   if (x == y ) {
        •    break@label
        •   }
        •  }
      • continue
        • label@ for (x in 0..8) {
        •  for (y in 0..8) {
        •   if (x == y ) {
        •    continue@label
        •   }
        •  }
        • }
    • Functions

      • Function declarations
      • Named arguments
        • fun add(a: Int, b: Int): Int {
        •  return a + b
        • }
      • Default arguments
        • fun add(a: Int, b: Int, c: Int = 1): Int {
        •  return a + b + c
        • }
      • Variable-length arguments
        • fun add(vararg numbers: Int): Int {
        •  var total = 0.0
        •  for (number in numbers) {
        •   total += number
        •  }
        •  return total
        • }
      • Expression functions
        • fun area(x: Int, y: Int) = x * y
      • Local functions
        • fun func() {
        •  fun func() {
        •  }
        • }
      • Anonymous functions
        • val oneF = fun(x: Int, y:Int): Int = x * y
  3. Object-oriented programming

    • Classes

    • Encapsulation
    • Inheritance
    • Polymorphism
    • Abstract classes/interfaces
  4. Functional programming

    • Higher-order functions
    • Lambda
    • Closures
    • Inline functions
    • Generics
    • Data containers
    • Functional APIs
  5. Common patterns

    • Exception handling
    • Threads
    • Coroutines
    • I/O
    • File management
    • Network programming
    • GUI programming
  6. Java features

    • Reflection
    • Annotations