gpt4 book ai didi

kotlin - 如何更改默认推断没有接收者的函数类型?

转载 作者:行者123 更新时间:2023-12-03 07:52:09 25 4
gpt4 key购买 nike

有人可以举个例子来说明它的含义吗?

当我读 Kotlin docs 时关于 lambda 函数,有一个绿色框表示:

A function type with no receiver is inferred by default, even if avariable is initialized with a reference to an extension function. Toalter that, specify the variable type explicitly.

仅供引用,下面的代码位于绿色框的顶部,因此应该与之相关:

val repeatFun: String.(Int) -> String = { times -> this.repeat(times) }
val twoParameters: (String, Int) -> String = repeatFun // OK

fun runTransformation(f: (String, Int) -> String): String {
return f("hello", 3)
}
val result = runTransformation(repeatFun) // OK

最佳答案

A function type with no receiver is inferred by default, even if a variable is initialized with a reference to an extension function.

我会重申(如果有帮助的话):

当变量x声明时没有显式类型时,会被分配一个在其声明中带有接收者A.(B)->C的函数——推断的类型x(A,B)->C,但不是 A.(B)->C

示例:

fun Int.addThree(): Int = this + 3

//the type of x is inferred as `(Int)->Int`, not `Int.()->Int`
val x = Int::addThree

//"To alter that, specify the variable type explicitly"
val y: Int.()->Int = Int::addThree

我们可以通过以下方式进行测试:

println(3.x()) //does not compile! (Unresolved reference: x)
println(3.y()) //ok

本文档放在原来的位置,因为它的正上方有一个部分解释了“带有和不带有接收器的函数类型的非文字值如何互换”

//The value assigned to variable `a` — `::addTwo`,
// is a function reference,
// *NOT* a literal value of function type
fun addTwo(i: Int) = i + 2
val a = ::addTwo

//The value assigned to variable `b` — `AddTwo()`,
// is an instance of a custom class that implements the function type as an interface,
// *NOT* a literal value of function type
class AddTwo : (Int) -> Int {
override fun invoke(i: Int): Int {
return i + 2
}
}
val b = AddTwo()

//The value assigned to variable `c` — `a`
// is a variable of function type,
// *NOT* a literal value of function type
val c = a

//The value assigned to variable `d` — `{ i:Int -> i + 2 }`,
// is a lambda expression,
// *IS* a literal value of function type
val d = { i:Int -> i + 2 }

//The value assigned to variable `e` — `fun(i: Int): Int { return i + 2 }`
// is an anonymous function,
// *IS* a literal value of function type
val e = fun(i: Int): Int { return i + 2 }

演示:

val a0: (Int)->Int = AddTwo()                          //OK
val b0: (Int)->Int = ::addTwo //OK
val c0: (Int)->Int = a //OK
val d0: (Int)->Int = { i:Int -> i + 2 } //OK
val e0: (Int)->Int = fun(i: Int): Int { return i + 2 } //OK

//"Non-literal values of function types with and without a receiver are interchangeable"
val a1: Int.()->Int = AddTwo() //OK
val b1: Int.()->Int = ::addTwo //OK
val c1: Int.()->Int = a //OK
val d1: Int.()->Int = { i:Int -> i + 2 } //ERROR: Expected no parameters
val e1: Int.()->Int = fun(i: Int): Int { return i + 2 } //ERROR: Expected no parameters

关于kotlin - 如何更改默认推断没有接收者的函数类型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/76918642/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com