我试图弄清楚如何在 Scala 中做到这一点
我有一个
List( MyObject(id, name, status), ..., MyObject(id, name, status) )
我想对这个集合应用一个函数,以获得一个包含 MyObjects 的所有“id”属性的列表
List( id1, id2, .., idN)
我想要类似于 Ruby 的注入方法的东西:
list.inject( [] ){ |lst, el| lst << el }
有什么建议吗?
我试图弄清楚如何在 Scala 中做到这一点
我有一个
List( MyObject(id, name, status), ..., MyObject(id, name, status) )
我想对这个集合应用一个函数,以获得一个包含 MyObjects 的所有“id”属性的列表
List( id1, id2, .., idN)
我想要类似于 Ruby 的注入方法的东西:
list.inject( [] ){ |lst, el| lst << el }
有什么建议吗?
You can use List's (actually, TraversableLike's) map function, as follows: list.map(_.id).
There are a wealth of useful methods like this available to the Scala collection classes - well worth learning.
在这种情况下,使用list.map(_.id)是最好的解决方案。显然,还有许多其他方法可以做到这一点。为了更好地理解,以下是两个例子。
将所选元素添加到数组中,例如:
> list = [1,2,3]
=> [1,2,3]
> list.inject([]) { |list,el| list << "Element #{el}" if (el % 2 == 0); list }
=> ["Element 2"]
可以在 Scala 中实现为:
> val list = List(1,2,3)
list: List[Int] = List(1, 2, 3)
> val map = list.map(x => if (x % 2 == 0) Some(s"Element $x") else None).flatten
map: List[String] = List(Element 2)
在将 Ruby 代码注入哈希之后:
> list = [1,2,3]
=> [1,2,3]
> list.inject({}) { |memo,x| memo[x] = "Element #{x}"; memo }
=> {1=>"Element 1", 2=>"Element 2", 3=>"Element 3"}
可以在Scala中完成:
> val list = List(1,2,3)
list: List[Int] = List(1, 2, 3)
> val map = list.map(x => (x -> s"Element $x")).toMap
map: scala.collection.immutable.Map[Int,String] = Map(1 -> Element 1, 2 -> Element 2, 3 -> Element 3)