且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何在scala中将枚举转换为Seq / List?

更新时间:2023-01-16 10:11:38

使用JavaConverters

请参见https://***.com/a/5184386/133106

使用包装器迭代器

您可以构建包装器:

val nameIterator = new Iterator[SomeType] { def hasNext = names.hasMoreElements; def next = names.nextElement }

使用JavaConversions包装器

val nameIterator = new scala.collection.JavaConversions.JEnumerationWrapper(names)

使用隐式JavaConversions

如果导入

import scala.collection.JavaConversions._

您可以隐式地执行此操作(并且您还将获得其他Java collecitons的隐式转换)

you can do it implicitly (and you’ll also get implicit conversions for other Java collecitons)

request.getParameterNames.map(println)

连续使用Iterator

您可能很想使用 Iterator.continuously 构建一个迭代器,就像该答案的早期版本一样:

You might be tempted to build an iterator using Iterator.continually like an earlier version of this answer proposed:

val nameIterator = Iterator.continually((names, names.nextElement)).takeWhile(_._1.hasMoreElements).map(_._2)

但是我t是不正确的,因为枚举器的最后一个元素将被丢弃。
原因是 takeWhile 中的 hasMoreElement 调用是在调用之后执行的中的nextElement 不断地,从而丢弃最后一个值。

but it's incorrect as the last element of the enumerator will be discarded. The reason is that the hasMoreElement call in the takeWhile is executed after calling nextElement in the continually, thus discarding the last value.