我有这个密封类PictureEvent
:
sealed class PictureEvent {
data class PictureCreated(val pictureId: String, val url: String) : PictureEvent()
//more classes extending PictureEvent
}
现在,从PictureEvent
s 列表中,我想获得第一个PictureCreated
:
fun doSomething(events: List<PictureEvent>) {
val creationEvent = events.first { isCreationEvent(it) } as PictureEvent.PictureCreated
//do stuff with the creationEvent
}
private fun isCreationEvent(event: PictureEvent) : Boolean {
return event is PictureEvent.PictureCreated
}
它工作正常。如您所见,我将事件转换为PictureCreated
(使用as
关键字),因为first
方法返回一个PictureEvent
. 我想知道是否可以通过使用 Kotlin 合约来避免这种转换。
我试过这个:
private fun isCreationEvent(event: PictureEvent) : Boolean {
contract {
returns(true) implies (event is PictureEvent.PictureCreated)
}
return event is PictureEvent.PictureCreated
}
但它不起作用;first
方法不断返回 a PictureEvent
,而不是PictureCreated
. 目前有可能做到这一点吗?