假设我有两个具有相同方法名称和签名的接口(interface),并且其参数具有默认值,由单个类实现,则会出现编译错误:
More than one overridden descriptor declares a default value for 'value-parameter b: Boolean = ... As the compiler can not make sure these values agree, this is not allowed.
例如:
interface A {
fun f(b: Boolean = true)
}
interface B {
fun f(b: Boolean = false)
}
class C : A, B {
override fun f(b: Boolean) {
}
}
有办法解决这个问题还是我应该定义两种不同的方法
最佳答案
你不能这样做。因为实现者方法不能有默认值。如果您使用 C().f()
编译器如何知道使用哪个默认值?
因为 C()
是一个 A
并且它也是一个 B
。
C().f()
必须调用 C.f(true)
因为 true 是 A 中的默认值。
和
C().f()
还必须调用 C().f(false)
因为 false 是 B 中的默认值。
所以这是一个冲突并且是不允许的。
你可以这样做来实现你想要的:
interface A {
fun f(b)
fun f(){f(true)}
}
interface B {
fun f(b)
fun f(){f(false)}
}
class C : A, B {
override fun f(b: Boolean) {
}
override fun f() {
// now you can define which default value is used for class C
// You can define either true or false
f(true)
}
}
关于android - Kotlin,使用相同的方法实现两个接口(interface)并具有默认值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69360251/