与Kotlin中高阶函数的参数混淆

时间:2018-10-23 07:27:11

标签: kotlin

在Kotlin中,我编写了以下代码,调用了fold函数。

fun operation(acc: Int, next: Int): Int {
    return acc * next
}
val items = listOf(1, 2, 3, 4, 5)
println(items.fold(1, ::operation))

在以上代码的第5行中,fold函数使用operation函数。

这是合理的,因为fold函数被声明为接受正好带有两个参数的函数引用或lambda(来自Kotlin stdlib fold的以下_Collections.kt实现的第三行)

public inline fun <T, R> Iterable<T>.fold(
        initial: R, 
        operation: (acc: R, T) -> R
): R {
    var accumulator = initial
    for (element in this) accumulator = operation(accumulator, element)
    return accumulator
}

让我感到困惑的是,fold函数还可以与如下所示的单参数函数Int::times一起使用。

val items = listOf(1, 2, 3, 4, 5)
println(items.fold(1, Int::times))

AFAIK,Int::times被声明为一个单参数成员函数,如下所示:

/** Multiplies this value by the other value. */
public operator fun times(other: Int): Int

我不太了解这个矛盾。与关键字operator有什么关系?

1 个答案:

答案 0 :(得分:0)

Sequelize.DATE

(或更具体地说,public operator fun times(other: Int): Int )实际上是::times类型,与Int.(Int) -> Int相同。这样就可以将(Int, Int) -> Int::times::operator一起使用。

相关问题