Добавил:
Upload Опубликованный материал нарушает ваши авторские права? Сообщите нам.
Вуз: Предмет: Файл:
Programming_in_Scala,_2nd_edition.pdf
Скачиваний:
26
Добавлен:
24.03.2015
Размер:
22.09 Mб
Скачать

Conclusion

Chapter 3 · Next Steps in Scala

102

spaces with the expression " " * numSpaces. Finally, you print out the information with the desired formatting. The entire script looks as shown in Listing 3.11:

import scala.io.Source

def widthOfLength(s: String) = s.length.toString.length

if (args.length > 0) {

val lines = Source.fromFile(args(0)).getLines().toList

val longestLine = lines.reduceLeft(

(a, b) => if (a.length > b.length) a else b

)

val maxWidth = widthOfLength(longestLine)

for (line <- lines) {

val numSpaces = maxWidth - widthOfLength(line) val padding = " " * numSpaces

println(padding + line.length +" | "+ line)

}

}

else

Console.err.println("Please enter filename")

Listing 3.11 · Printing formatted character counts for the lines of a file.

Conclusion

With the knowledge you’ve gained in this chapter, you should already be able to get started using Scala for small tasks, especially scripts. In future chapters, we will dive into more detail in these topics, and introduce other topics that weren’t even hinted at here.

Cover · Overview · Contents · Discuss · Suggest · Glossary · Index

Соседние файлы в предмете [НЕСОРТИРОВАННОЕ]