如何使参数默认?

我发现默认的参数值不是默认的一个奇怪的情况:

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 } 

编译错误:

 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 

当你使用默认参数调用一个函数时,你仍然不能隐式地跳过它们,并且传递下面的参数,你只能使用显式的命名参数来做到这一点。

例:

 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