println之前的双冒号在kotlin中是什么意思 [英] What does the double colon before println mean in kotlin

查看:237
本文介绍了println之前的双冒号在kotlin中是什么意思的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在下面的Kotlin代码中,println之前的双冒号是什么意思?

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

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

代码显示:

第一个属性:你好

First property: hello

推荐答案

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

创建成员引用或类引用.

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

这篇关于println之前的双冒号在kotlin中是什么意思的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆