函数是 Kotlin 中的实例吗?
Are functions instance in Kotlin?
我正在阅读 Kotlin documentation about lambda 并看到一行内容
To call fold we need to pass it an instance of the function type as an
argument
这给了我两个主要问题。
什么是函数实例(或函数类型)
函数(函数类型)怎么会有实例
到处都找不到答案,请帮忙。
- What is an instance of a function (or a function type)
函数类型被描述为 (Parameters) -> Result
,它的一个实例
将是实现与该类型描述匹配的签名的任何函数。
val function: (Int, Int) -> Int = { a, b -> a + b }
- How can functions (function type) have an instance
就像java中的匿名类一样,函数可以表示为内联对象。
例如,在 java 中,您将拥有 Consumer<T>
SAM-Type(单一抽象方法类型),它只有 accept(T): void
方法。在 kotlin 中,该类型是 (T) -> Unit
并且使用 lambda 表达式作为 var consumer: (T) -> Unit = { println(it) }
或函数引用创建它的实例。然后通过调用运算符 consumer(x)
或调用函数 consumer.invoke(x)
.
调用实例
我正在阅读 Kotlin documentation about lambda 并看到一行内容
To call fold we need to pass it an instance of the function type as an argument
这给了我两个主要问题。
什么是函数实例(或函数类型)
函数(函数类型)怎么会有实例
到处都找不到答案,请帮忙。
- What is an instance of a function (or a function type)
函数类型被描述为 (Parameters) -> Result
,它的一个实例
将是实现与该类型描述匹配的签名的任何函数。
val function: (Int, Int) -> Int = { a, b -> a + b }
- How can functions (function type) have an instance
就像java中的匿名类一样,函数可以表示为内联对象。
例如,在 java 中,您将拥有 Consumer<T>
SAM-Type(单一抽象方法类型),它只有 accept(T): void
方法。在 kotlin 中,该类型是 (T) -> Unit
并且使用 lambda 表达式作为 var consumer: (T) -> Unit = { println(it) }
或函数引用创建它的实例。然后通过调用运算符 consumer(x)
或调用函数 consumer.invoke(x)
.