在Scala中是否有一种优雅的方式可以同时收集和转换类型

时间:2016-07-20 12:45:02

标签: scala collections

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

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)
}

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

2 个答案:

答案 0 :(得分:2)

怎么样

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

答案 1 :(得分:2)

我想这取决于你发现的优雅。你是多么确定publicProp的所有值都是字符串。

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