What does the double colon before println mean in kotlin

后端 未结 1 1675
我在风中等你
我在风中等你 2020-12-19 17:38

What does the double colon before println mean in the Kotlin code below?

class InitOrderDemo(name: String) {
   val firstProperty = \"First pro         


        
相关标签:
1条回答
  • 2020-12-19 18:08

    From Kotlin documentation :: means:

    creates a member reference or a class reference.

    In your example it's about member reference, so you can pass a function as a parameter to another function (aka First-class function).

    As shown in the output you can see that also invoked println with the string value, so the also function may check for some condition or doing some computation before calling println. You can rewrite your example using lambda expression (you will get the same output):

    class InitOrderDemo(name: String) {
       val firstProperty = "First property: $name".also{value -> println(value)}
    } 
    

    You can also write your own function to accept another function as an argument:

    class InitOrderDemo(name: String) {
        val firstProperty = "First property: $name".also(::println)
        fun andAlso (block : (String) -> Int): Int{
            return block(firstProperty)
        }
    }
    
    fun main(args : Array<String>) {
        InitOrderDemo("hello").andAlso(String::length).also(::println) 
    }
    

    Will print:

    First property: hello

    21

    0 讨论(0)
提交回复
热议问题