将枚举转换为迭代器

Pet*_*ler 5 generics iterator enumeration scala type-inference

我有以下隐式转换 java.util.Enumerations

   implicit def enumerationIterator[A](e : Enumeration[A]) : Iterator[A] = {
     new Iterator[A] {
        def hasNext = e.hasMoreElements
        def next = e.nextElement
        def remove = throw new UnsupportedOperationException()
     }
   }
Run Code Online (Sandbox Code Playgroud)

不幸的是它不起作用,ZipFile.entries因为它返回一个Enumeration<? extends ZipEntry>(参见相关问题)并且Scalac一直告诉我

type mismatch; found : java.util.Iterator[?0] 
   where type ?0 <: java.util.zip.ZipEntry 
   required: Iterator[?]
Run Code Online (Sandbox Code Playgroud)

我无法弄清楚如何使对话工作.喜欢

List.fromIterator(new ZipFile(z).entries))
Run Code Online (Sandbox Code Playgroud)

Jam*_*Iry 7

List.fromIterator需要一个scala.Iterator但你的隐式返回一个java.util.Iterator.

这有效

import java.util.Enumeration

implicit def enum2Iterator[A](e : Enumeration[A]) = new Iterator[A] {
  def next = e.nextElement
  def hasNext = e.hasMoreElements
}

import java.util.zip.{ZipFile, ZipEntry}
val l = List.fromIterator(new ZipFile(null:java.io.File).entries)
Run Code Online (Sandbox Code Playgroud)

在顶部添加一个导入可防止编译

import java.util.Iterator
Run Code Online (Sandbox Code Playgroud)

有一些关于通过使用java.util.Iterator在2.8中统一Scala和Java的讨论.在缺点方面,Java的Iterator有一个删除方法,这对Scala的不可变集合没有任何意义.UnsupportedOperationException异常?布莱什!在正面方面,这样的错误会消失.

编辑:我添加了一个Trac问题,如果它说"必需:scala.Iterator [?]" https://lampsvn.epfl.ch/trac/scala/ticket/2102,错误信息会更清楚