Differences
This shows you the differences between two versions of the page.
| Both sides previous revision Previous revision Next revision | Previous revision | ||
|
pp:scalalab1 [2022/04/30 09:29] vbadoiu |
pp:scalalab1 [2022/05/07 17:26] (current) mihai.calitescu fixed typo |
||
|---|---|---|---|
| Line 5: | Line 5: | ||
| * practice writing **tail-recursive** functions as an alternative to imperative **loops** | * practice writing **tail-recursive** functions as an alternative to imperative **loops** | ||
| * keep your code clean and well-structured. | * keep your code clean and well-structured. | ||
| + | |||
| + | ** Make sure you have done your [[pp:scala-environment | scala environment]] setup ready ** | ||
| ** Create a new Scala worksheet to write your solutions ** | ** Create a new Scala worksheet to write your solutions ** | ||
| Line 122: | Line 124: | ||
| </code> | </code> | ||
| - | ===== II. Scala in practice ===== | + | ===== III. Scala in practice ===== |
| - | 1.1 Interacting with the filesystem. Scala uses Java implementations for using most of the operating system's functionalities. In the snippet below, we see the usage of the Java File class. | + | Objectives: |
| + | * See some very simple examples of real world Scala | ||
| - | <code Scala> | + | **3.1** Interacting with the filesystem. Scala uses Java implementations for using most of the operating system's functionalities. In the snippet below, we see the usage of the Java File class. |
| - | def getListOfFiles(dir: String):List[File] = { | + | |
| - | val d = new File(dir) | + | |
| - | if (d.exists && d.isDirectory) { | + | |
| - | d.listFiles.filter(_.isFile).toList | + | |
| - | } else { | + | |
| - | List[File]() | + | |
| - | } | + | |
| - | } | + | |
| - | </code> | + | |
| <code Scala> | <code Scala> | ||
| - | scala> import java.io.File | ||
| import java.io.File | import java.io.File | ||
| + | val someFile = new File("somefile.txt") | ||
| + | val fileSize = someFile.length | ||
| </code> | </code> | ||
| + | |||
| + | For this exercise we will want to implement a function that receives two files and returns the file with the maximum size. | ||
| + | |||
| + | **3.2** Starting from the snippet below which defines a main function (the entry point of a program) in Scala. we want to make a standalone program that prints the size of a file given as an argument. | ||
| <code Scala> | <code Scala> | ||
| - | scala> val files = getListOfFiles("/tmp") | + | object Main { |
| - | files: List[java.io.File] = List(/tmp/foo.log, /tmp/Files.scala.swp) | + | def main(args: Array[String]): Unit = { |
| + | println("Hello, Scala developer!") | ||
| + | if (args.length == 0) { | ||
| + | println("No parameter :(") | ||
| + | } else { | ||
| + | val filename = args(0) | ||
| + | } | ||
| + | } | ||
| + | } | ||
| </code> | </code> | ||
| - | |||