Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/variables/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
具有默认函数参数值的Kotlin接口_Kotlin - Fatal编程技术网

具有默认函数参数值的Kotlin接口

具有默认函数参数值的Kotlin接口,kotlin,Kotlin,我希望在实现接口的类中为函数参数使用默认值,如下所示: 接口文件存储服务{ fun storeFile(路径:字符串,负载:InputStream,类型:MediaType,替换:Boolean=true) } class LocalFileStoreService:FileStoreService{ 重写存储文件(路径:字符串,负载:InputStream,类型:MediaType,替换:Boolean/*??*/){ // .... } } 下面是编译的内容和未编译的内容: KO:不允许

我希望在实现接口的类中为函数参数使用默认值,如下所示:

接口文件存储服务{
fun storeFile(路径:字符串,负载:InputStream,类型:MediaType,替换:Boolean=true)
}
class LocalFileStoreService:FileStoreService{
重写存储文件(路径:字符串,负载:InputStream,类型:MediaType,替换:Boolean/*??*/){
// ....
}
}
下面是编译的内容和未编译的内容:

KO:不允许重写函数为其参数指定默认值

class LocalFileStoreService:FileStoreService{
重写存储文件(路径:字符串,有效负载:InputStream,类型:MediaType,替换:Boolean=true){
// ....
}
}
KO:类“LocalFileStoreService”不是抽象的,并且未实现抽象成员公共抽象存储文件(路径:字符串,负载:InputStream,类型:MediaType):fqn…FileStoreService中定义的单元

class LocalFileStoreService:FileStoreService{
重写存储文件(路径:字符串,有效负载:InputStream,类型:MediaType,替换:布尔){
// ....
}
}
正常

class LocalFileStoreService:FileStoreService{
重写存储文件(路径:字符串,负载:InputStream,类型:MediaType){
storeFile(路径、有效负载、类型、true)
}
重写存储文件(路径:字符串,有效负载:InputStream,类型:MediaType,替换:布尔){
// ....
}
}
这是预期的行为吗?
有没有更好的方法来管理接口中的默认参数值?

您所描述的很奇怪,因为通过尝试用Kotlin 1.4.20重现它,我看不到相同的行为

以下代码工作正常:

interface Test {
    fun test(p1: String, p2: Boolean = true)
}

class TestImpl : Test {
    // below commented function breaks compilation
    //override fun test(p1: String) = println("That's odd... received: $p1")

    // You cannot overwrite default value, that would break interface contract
    override fun test(p1: String, p2: Boolean) = println("It works ! Received: $p1 and $p2")
}

fun main() {
    // Default value for second parameter is deduced from interface signature 
    TestImpl().test("Hello")
}
如果我取消对没有布尔参数的函数的注释,编译将崩溃,因为该方法不从接口继承

一般来说,如果在接口级别定义默认值,那么更改特定实现的默认值将是一个坏主意,因为这将破坏API契约

编辑

请注意,从注释函数中删除override关键字将生成有效代码,因为它将成为特定于实现的函数。不过,我觉得这种行为很危险,因为以下程序:

interface Test {
    fun test(p1: String, p2: Boolean = true)
}

class TestImpl : Test {
    fun test(p1: String) = println("That's odd... received: $p1")
    override fun test(p1: String, p2: Boolean) = println("It works ! Received: $p1 and $p2")
}

fun main() {
    val t : Test = TestImpl()
    t.test("Hello")
    (t as TestImpl).test("Hello")
}
然后将生成此输出:

It works ! Received: Hello and true
That's odd... received: Hello

这只是一个改进问题的想法:只使用1或2个参数,不要使用特定于Java的类型,使您的示例真正最小化。谢谢。这的确很奇怪。我无法在新项目中重现该问题。不过,这些信息不是我写的……:)