斯卡拉'来自文件'的怪异? [英] Scala 'fromFile' weirdness?

查看:135
本文介绍了斯卡拉'来自文件'的怪异?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我无法理解为什么两个代码要做同样的事情,在Scala中做不同的事情。

I can't understand why two bits of code that are meant to do exactly the same thing, do different things in Scala.

第一个例子:

scala> val ggg = Source.fromFile("/somefile");
ggg: scala.io.BufferedSource = non-empty iterator

scala> ggg.getLines();
res67: Iterator[String] = empty iterator

第二个例子:

scala> Source.fromFile("/somefile").getLines();
res68: Iterator[String] = non-empty iterator

不是他们打算做同样的事情,或者我错过了什么?

推荐答案

这似乎是一个怪癖( bug?)与 BufferedSource.toString 。观察:

This seems to be a quirk (bug?) with BufferedSource.toString. Observe:

// no problem
scala> { val x = Source.fromFile("foo.txt"); x.getLines() }
res10: Iterator[String] = non-empty iterator

// ahh, calling toString somehow emptied our iterator
scala> { val x = Source.fromFile("foo.txt"); println(x.toString); x.getLines() }
non-empty iterator
res11: Iterator[String] = empty iterator

要显示表达式的值,REPL需要调用 BufferedSource.toString ,这会产生清空迭代器的副作用。

To show the value of the expression, the REPL needs to call BufferedSource.toString, and this has the side effect of emptying the iterator.

这篇关于斯卡拉'来自文件'的怪异?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆