Kotlin 如何将参数设为默认值?
我发现默认参数值不是默认值的奇怪情况:Kotlin 如何将参数设为默认值?,kotlin,Kotlin,我发现默认参数值不是默认值的奇怪情况: class Dog class DogHouse(dog: Dog) inline fun <T: Any, A: Any> build(sth: String = "", call: (A) -> T) {} fun main(args: Array<String>) { build(call = ::DogHouse) build(::DogHouse) // This line fails to c
class Dog
class DogHouse(dog: Dog)
inline fun <T: Any, A: Any> build(sth: String = "", call: (A) -> T) {}
fun main(args: Array<String>) {
build(call = ::DogHouse)
build(::DogHouse) // This line fails to compile
}
类狗
班级狗屋(狗:狗)
内联有趣构建(sth:String=”“,调用:(A)->T){
趣味主线(args:Array){
构建(调用=::DogHouse)
build(::DogHouse)//此行无法编译
}
编译错误:
Error:(11, 5) Kotlin: Type inference failed: inline fun <T : Any, A : Any> build(sth: String = ..., call: (A) -> T): Unit
cannot be applied to
(KFunction1<@ParameterName Dog, DogHouse>)
Error:(11, 11) Kotlin: Type mismatch: inferred type is KFunction1<@ParameterName Dog, DogHouse> but String was expected
Error:(11, 21) Kotlin: No value passed for parameter call
错误:(11,5)Kotlin:类型推断失败:内联趣味构建(sth:String=…,调用:(A)->T):单位
不能应用于
(功能1)
错误:(11,11)Kotlin:类型不匹配:推断的类型为KFunction1,但应为字符串
错误:(11,21)Kotlin:没有为参数调用传递值
当使用默认参数调用函数时,仍然不能隐式跳过它们并传递以下参数,只能使用显式命名参数来完成此操作
例如:
fun f(x: Int, y: Double = 0.0, z: String) { /*...*/ }
- 始终可以将
作为非命名参数传递,因为它位于默认参数之前:x
f(1, z = "abc")
- 当然,您可以按顺序传递所有参数:
f(1, 1.0, "abc")
- 但您不能跳过默认参数并在没有明确标签的情况下传递其后面的参数:
f(1, "abc") // ERROR f(1, z = "abc") // OK
fun g(x: Int = 0, action: () -> Unit) { action() }
g(0) { println("abc") }
g { println("abc") } // OK