【问题标题】:Is there an elegant way do collect and convert the type at the same time in Scala有没有一种优雅的方式在 Scala 中同时收集和转换类型
【发布时间】:2016-07-20 12:45:01
【问题描述】:

我有一个可以归为不同类别的属性列表。值类型不同。但不同的类别可能具有相同的值类型。

val data: List[(String, Any)] = List("first name" -> "rockie", 
                                     "last name" -> "yang",
                                     "address" -> "rather not reveal",
                                     "wanted age" -> 23)

val publicProps = Set("first name", "last name")
val privateProps = Set("address", "wanted age")

val filtered = data.filter(d => publicProps.contains(d._1))

// but the type of filtered is List[(String, Any)]

// I could do a map to convert the type to List[(String, String)]
filtered.map{case (name, value: String) => name -> value}

// If the number of publicProps is small
// I could do collect and convert at the same type
data.collect {
    case ("first name", value: String) =>
        ("first name", value)
    case ("last name", value: String) =>
        ("last name", value)
}

有没有一种优雅的方式来收集和转换同一类型的类型?

【问题讨论】:

    标签: scala collections


    【解决方案1】:

    我想这取决于你觉得什么是优雅的。以及您如何确定 publicProp 的所有值都是字符串。

    data.collect {
        case (key, value: String) if publicProps.contains(key) => (key, value)
    }
    

    【讨论】:

    • 非常感谢。因为我确定它是字符串,所以我需要同时转换时间。
    【解决方案2】:

    怎么样

    data.collect {
       case (k, v: String) if publicProps.contains(k) => (k, v)
    }
    

    【讨论】:

    • 你不需要“包含”。 .. if publicProps(k) => ... 会更“优雅” ;)
    • @Dima 对,那会更短。我仍然觉得contains 更具可读性:)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-02-07
    • 2010-12-20
    • 1970-01-01
    • 1970-01-01
    • 2011-09-18
    • 1970-01-01
    • 2020-04-14
    相关资源
    最近更新 更多