【问题标题】:Why can't a data class conform to an interface if its property conforms to the interface's property's interface?如果数据类的属性符合接口的属性的接口,为什么它不能符合接口?
【发布时间】:2020-03-16 18:03:20
【问题描述】:
interface BarInterface {
    val bar: Int
}

interface FooBarInterface {
    var foo: BarInterface
}

data class Bar(override val bar: Int): BarInterface {}

data class FooBar(override val foo: Bar): FooBarInterface {}

失败

Var-property public open val foo: Bar defined in FooBar cannot be \
overridden by val-property public abstract var foo: \
BarInterface defined in FooBarInterface
Type of 'foo' doesn't match the type of the overridden var-property \
'public abstract var foo: BarInterface defined in FooBarInterface'

如何在保持接口/数据类方法的同时解决这个问题?

【问题讨论】:

  • 我猜是用override var而不是override val吧?

标签: android kotlin interface


【解决方案1】:

我尝试了一些方法,我认为我目前最好的方法是

interface BarInterface {
    val bar: Int
}

interface FooBarInterface {
    var _foo: BarInterface
    val foo get() = _foo
}

data class Bar(override val bar: Int): BarInterface {}

data class FooBar(override val foo: Bar): FooBarInterface {
    override var _foo: BarInterface = foo
}

这让我可以做

val bar = Bar(bar = 1)
val fooBar = FooBar(foo = bar)
val barInterface: BarInterface = bar
val fooBarInterface: FooBarInterface = fooBar

print(fooBar.foo.bar)
print(fooBarInterface.foo.bar)

这不是很好,但很有效。

【讨论】:

    【解决方案2】:

    因为是var,所以下面的代码应该是合法的:

    class Bar2(override val bar: Int): BarInterface {}
    
    val fooBar: FooBarInterface = FooBar(Bar(0))
    fooBar.bar = Bar2(0)
    

    但是您将fooBar.bar 设置为Bar2,它只允许Bar(即使您更改为data class FooBar(override var foo: Bar))。

    FooBarInterface 中使用val bar 就可以了。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-06
      • 2010-09-20
      • 1970-01-01
      • 2021-06-28
      • 1970-01-01
      相关资源
      最近更新 更多