Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does the double colon before println mean in kotlin

Tags:

kotlin

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

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

The code prints:

First property: hello

like image 825
Ememobong AkpanEkpo Avatar asked Aug 11 '18 22:08

Ememobong AkpanEkpo


1 Answers

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

like image 118
O.Badr Avatar answered Oct 11 '22 16:10

O.Badr