Kotlin Notes - 3

发布时间 2023-11-19 22:56:00作者: Otlpy
  1. Function parameters can have default values, which are used when you skip the corresponding argument. This reduces the number of overloads:

    fun read(
        b: ByteArray,
        off: Int = 0,
        len: Int = b.size,
    ) { /*...*/ }
    
  2. If the last argument after default parameters is a lambda, you can pass it either as a named argument or outside the parentheses:

    fun foo(
        bar: Int = 0,
        baz: Int = 1,
        qux: () -> Unit,
    ) { /*...*/ }
    foo(1) { println("hello") }     // Uses the default value baz = 1
    foo(qux = { println("hello") }) // Uses both default values bar = 0 and baz = 1
    foo { println("hello") }        // Uses both default values bar = 0 and baz = 1
    
  3. You can name one or more of a function's arguments when calling it. This can be helpful when a function has many arguments and it's difficult to associate a value with an argument, especially if it's a boolean or null value.

    fun reformat(
        str: String,
        normalizeCase: Boolean = true,
        upperCaseFirstLetter: Boolean = true,
        divideByCamelHumps: Boolean = false,
        wordSeparator: Char = ' ',
    ) { /*...*/ }
    reformat(
        "String!",
        false,
        upperCaseFirstLetter = false,
        divideByCamelHumps = true,
        '_'
    )
    reformat(
        "String!",
        false,
        upperCaseFirstLetter = false,
        divideByCamelHumps = true,
        '_'
    )
    
  4. You can pass a variable number of arguments (vararg) with names using the spread operator:

    fun foo(vararg strings: String) { /*...*/ }
    foo(strings = *arrayOf("a", "b", "c"))
    
  5. When the function body consists of a single expression, the curly braces can be omitted and the body specified after an = symbol:

    fun double(x: Int): Int = x * 2
    
  6. Functions marked with the infix keyword can also be called using the infix notation (omitting the dot and the parentheses for the call).

    infix fun Int.shl(x: Int): Int { ... }
    
    // calling the function using the infix notation
    1 shl 2
    
    // is the same as
    1.shl(2)