且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

println之前的双冒号在kotlin中是什么意思

更新时间:2022-06-19 03:58:27

来自科特林文档 ::表示:

创建成员引用或类引用.

creates a member reference or a class reference.

在您的示例中,它是关于成员参考的,因此您可以将一个函数作为参数传递给另一个函数(aka

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

如输出所示,您可以看到also用字符串值调用了println,因此also函数可能会在调用println之前检查某些条件或进行某些计算. 您可以使用 lambda表达式( 您将获得相同的输出):

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) 
}

将打印:

第一个属性:你好

First property: hello

21