【问题标题】:How can you pattern match for several types, one of which is required, ala rust enums?您如何为多种类型进行模式匹配,其中一种是必需的,ala rust 枚举?
【发布时间】:2023-01-26 13:51:39
【问题描述】:

我需要一个变量,它可以是不同类型的几个必需值之一。 (假设是帖子、评论或社区)

在 Rust 中,你可以拥有枚举数据结构,它可以有多种类型,然后通过匹配语句提取它们的内部信息:https://doc.rust-lang.org/rust-by-example/custom_types/enum.html

我在 Kotlin 中发现的唯一可比较的是 Either 类型,但这仅限于两个值。 Kotlin 有什么可比的吗?

【问题讨论】:

标签: kotlin


【解决方案1】:

@IR42 的建议有效,不像生锈那么干净,但它是:

sealed class ItemType {
  class PostItem(val item: Post): ItemType()
  class CommentItem(val item: Comment): ItemType()
}
...
val x = ItemType.PostItem(post)
when(x) {
  is ItemType.PostItem -> x.item.post ...
  is ItemType.CommentItem -> x.item.comment ...
}

【讨论】:

    猜你喜欢
    • 2017-03-25
    • 1970-01-01
    • 1970-01-01
    • 2013-12-01
    • 1970-01-01
    • 2010-12-21
    • 2020-12-06
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多