首页 > 解决方案 > Kotlin 默认参数排序

问题描述

有谁知道为什么调用method1不编译而调用编译method2

class MyApp {

    interface X {

        fun <Q : Any, A : Any> method1(argStr: String = "", argQ: Q, argH: (A) -> Unit)

        fun <Q : Any, A : Any> method2(argQ: Q, argStr: String = "", argH: (A) -> Unit)
    }

    fun test(x: X) {

        /* Call to method1 does not work - the following errors are produced
         * Error: Kotlin: Type inference failed:
         * fun <Q : Any, A : Any> method1(argStr: String = ..., argQ: Q, argH: (A) -> Unit): Unit
         * cannot be applied to (Int,(Int) -> Unit)
         * Error: Kotlin: The integer literal does not conform to the expected type String
         * Error: Kotlin: No value passed for parameter 'argQ'
         */
        
        x.method1(1) { res: Int -> println(res) }

        /* No errors here */
        x.method2(1) { res: Int -> println(res) }
    }

}

标签: kotlindefault-parameters

解决方案


如果默认参数在没有默认值的参数之前,则只能通过使用命名参数调用函数来使用默认值

例子:

fun foo(bar: Int = 0, baz: Int) { ... }

foo(baz = 1) // The default value bar = 0 is used

在您的示例中,这将起作用:

x.method1(argQ = 1) { res: Int -> println(res) } // The default value argStr = "" is used

进一步阅读


推荐阅读