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
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With