layout: post
author: csiu
date: 2017-06-02
title: "Day98: Scala"
categories: update
tags:
  - 100daysofcode
excerpt: To learn how to programs in Scala.
---

Today I want to mess with Scala and be able to do the following:

### Task

For each `line` in a data file, I want to generate standard code around that `line`.
If this line matches some regular expression, I want to then add a few more things to that output.

### Purpose

To learn how to programs in Scala.

*(and because I sort of need to know this/ it would be a great help for my day job)*

### Getting started

> To execute script "my_script.scala", you need to run:<br>
> `scala /path/to/my_script.scala`

To start, we need to learn the Scala syntax for each component of the task:

```scala
// 1. Check that the script works by printing "Hello..."
println("Hello from the script")
```

```scala
// 2. Be able to access terminal arguments when you run
//        scala path/to/my_script.scala first_arg
println("This is my first argument: " + args(0))
```

```scala
// 3. Check that the first argument is a file
//    and do something if it is
val input_file = args(0)

import java.nio.file.{Paths, Files}
val isFile = Files.exists(Paths.get(input_file))

if (isFile) {
  println(f"'$input_file' is a file")
}
else {
  println(f"'$input_file' is not a file")
  System.exit(1)
}
```

```scala
// 4. Read a file line by line
scala.io.Source.fromFile(input_file).getLines().foreach {
  println
}
```

```scala
// 5. Define a function to produce a string
//    and be able to use it
def template(input_string: String) : String = {
  var blurb : String = f"Hello $input_string"
  return blurb;
}

// Use function
println(template("John Smith"))
```

```scala
// 6. Read a file line by line,
//    assign the line to a variable,
//    and use the line in a function
for (line <- scala.io.Source.fromFile(input_file).getLines()) {
  println(template(line))
}
```

```scala
// 7. Do something if a string matches some regex
val regrex_berry = """berry""".r

for (line <- scala.io.Source.fromFile(input_file).getLines()) {
  val isMatchLine = regrex_berry.findFirstIn(line).isDefined

  if (isMatchLine) {
    println(f"'$line' is a berry")
  }
}
```

<br>

## Putting it all together

Now that we have all the pieces, we can assemble the script:

<script src="https://gist.github.com/csiu/5ea94d521f1c54a1b44e84030e76d343.js"></script>
