我想写这样的东西:
/**
* Represents a state, large or small.
*/
interface State {
/**
*
*/
val changeValue: StateChange<This> // does not compile; "This" is a keyword I made up that might reference the implementing class
}
/**
* Represents a change in a state, large or small.
*
* @param StateType The type of state that has changed
*/
interface StateChange<StateType: State>
但是,正如我的评论所述,我不知道这个的语法。这是存在吗?或者我是否必须使用变通方法,例如强制State将其作为通用参数?
如果不明显,我无法使用val changeValue: StateChange<State>
,因为这样就可以了,我不想要这样做:
// BAD EXAMPLE - This is what I want to avoid
class Foo: State { val changeValue: StateChange<Bar> = Bar().changeValue }
class Bar: State { val changeValue: StateChange<Foo> = Foo().changeValue }
答案 0 :(得分:3)
您可以使用具有递归上限的类:
interface State<T : State<T>> {
val changeValue: StateChange<T>
}
interface StateChange<StateType: State<StateType>>
现在这段代码将不再编译:
class Foo: State<Foo> { val changeValue: StateChange<Bar> = Bar().changeValue }
class Bar: State<Bar> { val changeValue: StateChange<Foo> = Foo().changeValue }