为什么这个Scala for循环翻译不相同?

时间:2017-05-16 14:19:54

标签: scala for-loop

我尝试编写此代码

val req: mutable.Buffer[InterfaceHttpData] = /*...*/
for (attr: Attribute <- req) {
  println(attr.getValue())
}

这给了我以下错误:

type mismatch;
 found   : io.netty.handler.codec.http.multipart.Attribute => Unit
 required: io.netty.handler.codec.http.multipart.InterfaceHttpData => ?

我已经通读了the specs,据我所知,这个for循环应该等同于以下内容。

req.withFilter { case attr: Attribute => true; case _ => false }.foreach {
  case attr: Attribute => println(attr.getValue())
}

这个编译得很干净。我是否误解了for循环转换是如何完成的?

1 个答案:

答案 0 :(得分:0)

根据规范,只有当p中的p <- ee的类型无效时才会应用此转换,在您的示例中,(p: U) <- (e: F[T])表示T <: U scala> trait T defined trait T scala> class C extends T defined class C scala> val c: List[C] = Nil c: List[C] = List() scala> for (e: T <- c) println(e) scala> val t: List[T] = Nil t: List[T] = List() scala> for (e: C <- t) println(e) <console>:14: error: type mismatch; found : C => Unit required: T => ? for (e: C <- l) println(e) ^ }}

<iframe id="pdfFrame" name="pdf1" onload="LoadPrint();" 
style="height:1000px;width:1000px;"></iframe>

<script type="text/javascript">

function LoadPDF(filename)
{
    var loc = "pdf-loader.html?pdfframe="+filename;
    document.getElementById("pdf").setAttribute("src", loc);
}

function LoadPrint() {
    alert('fired!');
    if (document.getElementById("pdf").src !== "") {
        var frm = document.getElementById("pdf");
    frm.contentDocument.getElementById("pdfframe").contentWindow.print();
    }
}

</script>
相关问题