- Learn Scala Programming
- Slava Schmidt
- 370字
- 2021-06-10 19:35:41
View
View has been reimplemented in the new version of the library. Now it represents a reified Iterator operations.
This means that the Iterator methods are represented as a subclasses of View and encapsulate transformations to apply. The evaluation happens at the moment the view is converted to the strict collection type, or traversed, for example using the foreach method. Views don't remember the type of the source collection. This can be demonstrated by the following example. First, we define a generic transformation that might be strict or lazy, depending on the type of the collection given as an argument:
def transform[C <: Iterable[Char]](i: C): Iterable[Char] = i
map { c => print(s"-$c-"); c.toUpper }
take { println("\ntake"); 6 }
Next, for each transformation step, we print out its result in the console at the moment the step happens. Now we can compare lazy and strict collection behaviors:
val str = "Scala 2.13"
val view: StringView = StringView(str)
val transformed = transform(view) // A
val strict = transform(str.toList) // B
print("Lazy view constructed: ")
transformed.foreach(print) // C
print("\nLazy view forced: ")
println(transformed.to(List)) // D
println(s"Strict: $strict") // E
This snippet produces the following output in the REPL:
take
-S--c--a--l--a-- --2--.--1--3-
take
Lazy view constructed: -S-S-c-C-a-A-l-L-a-A- -
Lazy view forced: -S--c--a--l--a-- -List(S, C, A, L, A, )
Strict: List(S, C, A, L, A, )
In the first line, we can see that the take method is always evaluated strictly regardless of the underlying collection type—this is commented as A in the preceding code. The second and third lines show the strict evaluation for List[Char], line B in the code. Lines 4 and 5 demonstrate that View[Char] is then evaluated twice, each time at the moment it is forced, once by calling foreach (line C) and once by converting it to the List (line D). Also interesting is that map is only applied to the results of the take method even given the fact that map is the first transformation step in the chain.
- Facebook Application Development with Graph API Cookbook
- Vue.js 2 and Bootstrap 4 Web Development
- 動手玩轉(zhuǎn)Scratch3.0編程:人工智能科創(chuàng)教育指南
- 我的第一本算法書
- 用戶體驗增長:數(shù)字化·智能化·綠色化
- Visual C++開發(fā)入行真功夫
- Node.js:來一打 C++ 擴展
- SQL Server 2016 從入門到實戰(zhàn)(視頻教學版)
- Java EE 7 with GlassFish 4 Application Server
- 軟件工程與UML案例解析(第三版)
- Mastering JavaScript Promises
- 數(shù)據(jù)庫技術及應用教程上機指導與習題(第2版)
- Qt編程快速入門
- Java EE 7 First Look
- WebGIS之Leaflet全面解析