如何从枚举中创建Seq

Bla*_*man 1 scala sequence playframework

我的枚举看起来像:

object ContentType extends Enumeration {
  type ContentType = Value
  val BlogPost, KB, Link = Value
}
Run Code Online (Sandbox Code Playgroud)

现在我想使用此枚举创建一个下拉列表.

@helper.select(field = ContentForm("contentType"), options = @contentTypes)
Run Code Online (Sandbox Code Playgroud)

Play有一个@helper.select需要序列的方法,所以我添加了一个序列,我将传递给我的视图页面:

val contentTypes: Seq[(Int, String)] = ...
Run Code Online (Sandbox Code Playgroud)

如何从ContentType枚举中初始化或创建此序列?

更新

对不起,它必须是Seq [(String,String)]类型

End*_*Neu 5

我不清楚为什么你的val contentTypes类型Seq[(Int, String)],也许我错过了什么,但你可以Enumeration改为Seq:

scala> object ContentType extends Enumeration {
 |     type ContentType = Value
 |     val BlogPost, KB, Link = Value
 |   }
 defined module ContentType

scala> ContentType.values.toSeq
res0: Seq[ContentType.Value] = ArrayBuffer(BlogPost, KB, Link)
Run Code Online (Sandbox Code Playgroud)

编辑:

来自@Marth评论,使用zipWithIndexswap:

scala> ContentType.values.toSeq.map(_.toString).zipWithIndex.map(_.swap)
res5: Seq[(Int, String)] = ArrayBuffer((0,BlogPost), (1,KB), (2,Link))
Run Code Online (Sandbox Code Playgroud)

如果你想Seq[(String, String)]:

scala>  ContentType.values.toSeq.map(_.toString).zipWithIndex.map(tuple => (tuple._2.toString, tuple._1))
res6: Seq[(String, String)] = ArrayBuffer((0,BlogPost), (1,KB), (2,Link))
Run Code Online (Sandbox Code Playgroud)

一步步:

ContentType.values.toSeq
Run Code Online (Sandbox Code Playgroud)

返回a Seq[ContentType.Value],然后调用.map(_.toString)返回a Seq[String],你现在想要每个都String与一个数字标识符相关联,我们使用每个值的索引,zipWithIndex创建一个Seq元组,其中第一个值是String,第二个值是String所在的索引:

scala> ContentType.values.toSeq.map(_.toString).zipWithIndex
res7: Seq[(String, Int)] = ArrayBuffer((BlogPost,0), (KB,1), (Link,2)
Run Code Online (Sandbox Code Playgroud)

我们在那里,期望的类型是Seq[(String, String)]我们有的地方Seq[(String, Int)],请注意我也认为你希望元组是(index, value)我们现在拥有的类型(value, index),所以我们再次映射有两个原因,第一个交换值,第二个转换为转换字符串的索引:

scala>  ContentType.values.toSeq.map(_.toString).zipWithIndex.map(tuple => (tuple._2.toString, tuple._1))
res8: Seq[(String, String)] = ArrayBuffer((0,BlogPost), (1,KB), (2,Link))
Run Code Online (Sandbox Code Playgroud)

我们还可以缩短删除第一个映射的代码,该映射将我们的自定义类型转换为字符串并延迟toString最后一个映射中的调用,具有以下内容:

scala> ContentType.values.toSeq.zipWithIndex.map(tuple => (tuple._2.toString, tuple._1.toString))
res9: Seq[(String, String)] = ArrayBuffer((0,BlogPost), (1,KB), (2,Link))
Run Code Online (Sandbox Code Playgroud)