# Scala programming language

- Page: https://shared.btbytes.com/p/scala
- Date: 2019-09-11
- Tags: jvm, scala, programming-language

See Also: [Scala for Datascience](https://www.btbytes.com/scala4ds.html), [ScalaJS](https://www.btbytes.com/scalajs.html), coursier, [select-scala](https://shared.btbytes.com/p/select-scala)

July, 2015 -- [Scala book reviews](http://programming-digressions.blogspot.com/2015/07/best-scala-books-it-is-hard-enough-to.html)
Feb, 2018 -- [Recursion and Trampolines in Scala](https://gist.github.com/eamelink/4466932a11d8d92a6b76e80364062250)

# Random Notes

```
scala-cli—power repl -S 2.13 -A —ammonite-ver 2.5.11
```

# Notes from Programming in Scala

- [Code Examples for Programming in Scala, Second Edition](https://booksites.artima.com/programming_in_scala_2ed/examples/index.html)

## Chapter 7 - built-in control structures.

- has very few control structures
- `if while for try match` and function calls.
- scala accumulates control structs in libraries.
- use `val` instead of `var` wherever possible. makes it easy to refactor. "equational reasoning".
- no `=` sign while defining a function => returns a `Unit` value `()`
- `while` and `do-while` are NOT expressions. they return `Unit`.
- prefer NOT to use while.
- **for**
- "generator" syntax -- `file <- files`. works on all collections.
- `file` is a `val`.
- `Ranges` -- `1 to 4` (yields 1,2,3,4)
- `1 until 4` -- exlcude the upper bound (yields 1,2,3)
- generators can also include filters -- `for (f <- files if f.getName.endsWith('.py'))`
- nested iteration.
- mid-stream variable bindings
- new collection:

```scala
def pyFiles =
  for {
    file <- files
    if file.getName.endsWith('.py')
  } yield file
```
- **IMP**: don't put `yield` inside the curlies.

Exceptions:

```scala
try {


} catch {
  case ex: FileNotFoundException => //handle
  case ex: IOException => //handle
}
```
- like other control structures, `try-catch-finally` also results in a value. (this is unlike Java) //imp

Match:

```scala

val fruit =
    someArg match {
      case "foo" => "bar"
      case "banana" => "pepper"
      case _ => "what?"
}
```

## Chapter 8- Functions and Closures

First class functions

```(x: Int) => x+1```

named function:

```scala
var increase = (x: Int) => x + 1
```

- target typing: `someNumbersList.filter((x) => x > 0)`. the type is inferred from the the list of *integers*.
- alternatively: `someNumbersList.filter(x => x > 0)`

Placeholder syntax:

```scala
someNumbersList.filter( _ > 0)
```

```
val f = (_: Int) + (_: Int)
```


## Chapter 12 -- Traits

Traits are like java interfaces with concrete methods + declare fields and maintain state.

Traits can do everything classes can do, except --

1. trait cannot have any clas parameters (ie., those passed to primary constructors).
2. `super` calls are not statically bound.

Unlike Java, adding a concrete method to scala trait is an one-time effort.


## Chapter 15  -- Case classes and pattern matching

- [Scala Case Classes In Depth - Alessandro Lacava](http://www.alessandrolacava.com/blog/scala-case-classes-in-depth/)


----

# Notes from "Scala in Action"

## Chapter 2 -- Getting started

```
// working with arrays and Lists
@ val nList = 1 :: 2 :: 3 :: 4 :: Nil
nList: List[Int] = List(1, 2, 3, 4)
@ nList.fil
filter     filterNot
@ nList.filter( _ > 2)
res17: List[Int] = List(3, 4)

@ // for comprehensions
@ oldList
res19: List[Int] = List(1, 2)
@ newList
res20: List[Int] = List(1, 2, 3)
@ for { a <- oldList; b <- newList } println (a+b)
2
3
4
3
4
5
@ // above is imperative form
@ // The functional form for comprehension is:
@ // also called the sequence composition
@ for { a <- oldList; b <- newList } yield a+b
res22: List[Int] = List(2, 3, 4, 3, 4, 5)

@ // Pattern Matching
@ val x = 3
x: Int = 3
@ def ordinal(number: Int):  Unit = number match {
    case 0 => println("One")
    case 1 => println("Two")
    case 2 => println("Three")
    case 3 => println("Four")
    case _ => println("what is this?")
  }
defined function ordinal
@ ordinal(x)
Four

@ // Pattern Matching Types
@ dBef printType(obj: AnyRef) = obj match {
    case s: String => println("This is a string")
    case i: java.util.Date => println("This is a Date")
    case l: List[_] => println("An array eh?")
    case _ => println("dunno who ye are")
  }
defined function printType
@ printType(List(1,1,2))
An array eh?


// Guards
@ def numCatcher(num: Int): Unit = num match {
    case x if x < 10 => println("Number less than 10")
    case y if (y%2 == 0) => println("Is an even number")
  }
defined function numCatcher
@ numCatcher(5)
Number less than 10

@ numCatcher(12)
Is an even number


```

# Miscellaneous notes

[sbt](http://www.scala-sbt.org/) plays an important role in the day to
day programming of scala. I believe 'sbt' stood for "scala build tool"
at one time, but is no longer.

To start working on a scala program, you can start with a simple text
editor, however using something like [IntelliJ
IDEA](http://www.jetbrains.com/idea/) is probably far more productive.

Creating a "project structure" can be automated. Essentially this
boilBs down to creating the `build.sbt` file, `project` directory and
optional `plugins.sbt` file inside it, a scala file inside the proper
`src/main/scala/com/example/projectname/` directory etc., There is
little reason to do all this manually, except when you are trying to
understand the reason behind such a recommended directory layout.

[giter8](https://github.com/n8han/giter8) ie., the `g8` is a tool that
can create a project structure based on [pre-defined
templates](http://github.com/n8han/giter8/wiki/giter8-templates). Think
of this as `paster` tool for Python.

When you have `g8` installed, creating a new project (say, a basic
scala project using
[this template](https://github.com/fayimora/basic-scala-project.g8) ),
all you have to do is:

    $ g8 fayimora/basic-scala-project.g8

    A basic scala project

    name [Basic Project]: basic-scala
    organization [com.example]: com.btbytes
    version [0.0.1]:

    Template applied in ./basic-scala

    $ cd basic-scala
    $ ls
    build-sbt src

`$ sbt run` will download the dependencies defined in the `build.sbt`
file,B compile source and run the program.

sbt can also create the files necessary to make this an "IntelliJ IDEA
project". For this, we add a dependency to the `plugins.sbt` file:

    #project/plugins.sbt -- add this line
    addSbtPlugin("com.github.mpeltonen" % "sbt-idea" % "1.6.0")

Running `sbt gen-idea` will generate the IDEA project files (`.idea`,
some `.iml`).

Launch up IDEA and "open project" and open the root directory of the
project. You are now set to work on the code.

Packaging the binary to a `.jar`:

    $ sbt packageBin

Will produce `target/scala-2.10/basic-scala_2.10-0.0.1.jar` (where
`basic-scala` is the name of the project).

## Why not Scala

- [Scala, part II](http://evrl.com/programming/scala/2017/04/04/scala-part-ii.html)

## Concepts

### Covariance, Contravariance and Invariance

Reading:

- [Simple example for Scala Covariance, Contravariance and Invariance](http://web.archive.org/web/20200615014031/https://coderwall.com/p/dlqvnq/simple-example-for-scala-covariance-contravariance-and-invariance)

- **[Covariance and contravariance in Scala](http://blog.kamkor.me/Covariance-And-Contravariance-In-Scala/)**

>  In general, covariant type parameter can be used as immutable field type,
>  method return type and also as method argument type if the method argument
>  type has a lower bound. Because of those restrictions, covariance is most
>  commonly used in producers (types that return something) and immutable
>  types.

### Adhoc polymorphism

- [Ad hoc polymorphism in Scala for the mere mortals](https://blog.codecentric.de/en/2017/02/ad-hoc-polymorphism-scala-mere-mortals/)

> In this article we discussed the motivation for introducing ad hoc polymorphism and implementing it using the Type Class Pattern in Scala. It allows us to build abstractions which are completely decoupled from the underlying data types on which they operate. Hence we can implement polymorphic functions which operate on types we have no control over, such as types defined in the standard library or some other third party library, without sacrificing the static type safety.

### Concurrency (Akka etc.,)

- [Introduction to the Actor Model for Concurrent Computation: Tech Talks @ AppNexus - YouTube](https://www.youtube.com/watch?v=lPTqcecwkJg)

### StBreams

- [Folding Stream with Scala](http://voidmainargs.blogspot.ie/2011/08/folding-stream-with-scala.html)(2011).

## Libraries

- [scalaz-stream](https://github.com/scalaz/scalaz-stream) and related .. `Process[Task, A]`
- [Doobie](https://github.com/tpolecat/doobie) -- principled database access for scala
- [Monix](https://monix.io/) via Travis Brown on twitter for "exceptionally good documentation"
- [Easy Parsing with Parser Combinators](http://www.lihaoyi.com/post/EasyParsingwithParserCombinators.html) [HN](https://news.ycombinator.com/item?id=12450919)
- [ConsBcript](http://www.foundweekends.org/conscript/)  is a distribution mechanism for Scala apps using Github and Maven repositories as the infrastructure. You can use it to install and update apps similar to APT or Home Brew.
- [Knobs Documentation - Home](http://verizon.github.io/knobs/)

## Tools

- [lihaoyi/Ammonite: Scala Scripting](https://github.com/lihaoyi/Ammonite/). Ammonite enables shell-like scripting in the Scala programming language.
- [Conscript](https://github.com/n8han/conscript) -- is a tool for
  installing and updating Scala software programs.
- [giter8](https://github.com/n8han/giter8) -- is a command line tool
  to generate files and directories from templates published on github
  or any other git repository.

### SBT

- [all that jazz - sbt - A task engine](https://jazzy.id.au/2015/03/03/sbt-task-engine.html)
- [all that jazz - sbt - A declarative DSL](https://jazzy.id.au/2015/03/04/sbt-declarative-dsl.html)
- [52-technologies-in-2016/sbt](https://github.com/shekhargulati/52-technologies-in-2016/blob/master/02-sbt/README.md)
- [sbt the easy way](https://blog.codacy.com/sbt-the-easy-way-15f2fe65ad37#.vk1ohiod7) -- with example configurations.
- [Building Scala Projects: Maven vs. SBT · Hammer Lab](http://www.hammerlab.org/2017/04/06/scala-build-tools/)
- [sbt baby steps](https://www.slideshare.net/MarinaSigaeva/sbt-baby-steps) [Feb 2018]. SBT, scopes, proxy and so on

- <https://stackoverflow.com/questions/46271505/how-do-i-change-a-projects-id-in-sbt-1-0/46276523#46276523>

### [Ensime](http://github.com/aemoncannon/ensime) -- Enhanced Scala

Interaction Mode for Emacs.

- [ensime config error](https://github.com/ensime/ensime-server/issues/670)


## Talks

- [Compositionality](https://www.dropbox.com/s/0l7r5o7tczzx57m/Compositionality.pdf?dl=0) talk by Runorama.

## Articles

- [16 months of FP](http://www.vasinov.com/blog/16-months-of-functional-programming/) (with scala examples).
- [Scala’s Types of Types](http://ktoso.github.io/scala-types-of-types/)
- [Generalized type constraints in Scala](http://blog.bruchez.name/2015/11/generalized-type-constraints-in-scala.html)
- [Scala Saturday: Functions for the Object-Oriented – Medium](https://medium.com/@markcanlasnyc/scala-saturday-functions-for-the-object-oriented-4218f9ed192b#.alxnuxs0o) -- a beginner overview of some scala features (eg: how apply works).
- [Why? ](https://gitlab.com/snippets/1655955) by Paul Snively.
- [Transitioning to Scala – RedElastic](https://blog.redelastic.com/transitioning-to-scala-d1818f25b2b7) (notes on "Scala levels" as espoused by Odersky.)
- [Warts of the Scala Programming Language](http://www.lihaoyi.com/post/WartsoftheScalaProgrammingLanguage.html)
- [When the Scala compiler doesn't help](http://www.latkin.org/blog/2017/05/02/when-the-scala-compiler-doesnt-help/)

## Blogs

- [Bcomposes | (Scala, Java, Python, R)](http://bcomposes.wordpress.com/)
- [Just another scala quant](http://web.archive.org/web/20120508141057/http://www.jasq.org/)
- [Vladimir Pavkin – Scala developer at Evolution Gaming](http://pavkin.ru/)
- [alexn.org](https://alexn.org/) creator of Monix. see [Asynchronous Programming and Scala](https://alexn.org/blog/2017/01/30/asynchronous-programming-scala.html)
- [Julien Richard-Foy](http://julien.richard-foy.fr/blog/archives/) -- play, category-theory examples, dependency injection etc.,
- [Timothy Perrett](http://timperrett.com/)
- [Blog Archive | Madusudanan](https://madusudanan.com/archive/) -- scala posts.

## Libraries

- [kantan.csv](https://nrinaudo.github.io/kantan.csv/) has good documentation/tutorials.
- [Quill](https://getquill.io/#docs)  Quoted Domain Specific Language (QDSL) to express queries in Scala and execute them in a target language. The library’s core is designed to support multiple target languages, currently featuring specializations for Structured Query Language (SQL) and Cassandra Query Language (CQL).

## REPL

[Ammonite REPL](http://ammonite.io/#Ammonite-REPL) is much more featureful than the default REPL and comes with a lot of ergonomic improvements and configurability that may be familiar to people coming from IDEs or other REPLs such as IPython or Zsh.

* [Squeezing extra productivity out of Ammonite Scala REPL](https://blog.softwaremill.com/squeezing-extra-productivity-out-of-ammonite-scala-repl-b4e4001cca07)

## Links

- Cheatsheet - [Idiomatic Scala: Your Options Do Not Match - Originate Developer Blog](http://web.archive.org/web/20141006032701/http://blog.originate.com/blog/2014/06/15/idiomatic-scala-your-options-do-not-match)
- [Scala Starter Kit](http://www.cakesolutions.net/teamblogs/scala-starter-kit)
- [Essential Scala](http://underscore.io/training/courses/essential-scala/)
- [Code examples for "Programming in Scala" book by Odersky](https://www.cs.helsinki.fi/u/wikla/OTS/Sisalto/examples/)
- [Scala Exercises | The easy way to learn Scala](http://scala-exercises.47deg.com/)
- [λ Tony's blog λ - scala.Option Cheat Sheet](http://web.archive.org/web/20130429013704/http://blog.tmorris.net/posts/scalaoption-cheat-sheet)
- [Scala jargon – Bonnie Eisenman](http://blog.bonnieeisenman.com/blog/scala-jargon/)


## Scalajs

- [From first principles: Why I bet on Scala.js](http://www.lihaoyi.com/post/FromfirstprinciplesWhyIbetonScalajs.html)
- [vmunier/play-with-scalajs-example: Example application showing how you can integrate Play with Scala.js.](https://github.com/vmunier/play-with-scalajs-example)

## Scala Native

- [Hands On Scala Native](https://masseguillaume.github.io/hands-on-scala-native-slides/#/)
- [Stephen M. Blackburn and Kathryn S. McKinley. 2008. Immix: a mark-region garbage collector with space efficiency, fast collection, and mutator performance. In Proceedings of the 29th ACM SIGPLAN Conference on Programming Language Design and Implementation (PLDI '08). ACM, New York, NY, USA, 22-32.](http://users.cecs.anu.edu.au/~steveb/pubs/papers/immix-pldi-2008.pdf) [PDF].
- [Fast startup and low latency - pick two](https://github.com/densh/talks/blob/master/2017-06-01-fast-startup-and-low-latency.pdf) [PDF] by Denys Shabalin and Lukas Kellenberger.
- [Scala 0.3.0](https://redd.it/6hgnno) announcement

## Scala CLI

With `scala-cli`, it is quite easy to package a scala program into a standalone program:

`scala-cli --power package --native-image Echo.scala -o echo -- --no-fallback`

where `Echo.scala` is:

```scala
object Echo {
def main(args: Array[String]): Unit =
	println(args.mkString(" "))
}
```
```bash
$ ls -alrt echo
-rwxr-xr-x@ 1 pradeep  staff  14120984 Aug 23 17:15 echo
$ du -sh echo
 13M    echo
```

## Books

- [Scala Design Patterns](https://www.safaribooksonline.com/library/view/scala-design-patterns/9781785882500/)
* [Overview of Apache Spark · Mastering Apache Spark 2 (Spark 2.2+)](https://jaceklaskowski.gitbooks.io/mastering-apache-spark/content/spark-overview.html) by jace klaskowski
* [Introduction · Mastering Apache Kafka (0.11.0.1+)](https://jaceklaskowski.gitbooks.io/apache-kafka/) by jace klaskowski
* [Introduction · Spark Structured Streaming (Apache Spark 2.2+)](https://jaceklaskowski.gitbooks.io/spark-structured-streaming/) by jace klaskowski


## Tutorials

- [Learn Scala in Y Minutes](https://learnxinyminutes.com/docs/scala/)
- [The Neophyte's Guide to Scala - Daniel Westheide](http://danielwestheide.com/scala/neophytes.html)
- [bhoward/IndyScala](https://github.com/bhoward/IndyScala) Notebooks for the Scala Primer presentation to the Indy Scala meetup, September 2016.
- [Mark Lewis - YouTube](https://www.youtube.com/user/DrMarkCLewis/videos) tutorials on Scala and programming. [Dr. Lewis's Homepage](http://www.cs.trinity.edu/~mlewis/)
- [From Python to Scala: A Tutorial - Cristian Cardellino](http://crscardellino.me/from-python-to-scala/)

## Indyscala notes

### Feb 6, 2017 -- Resource management in Scala

Presenter -- Ross A. Baker

- [tut - Underscore](http://underscore.io/blog/posts/2015/12/18/tut.html)
- atomic boolean in
- codensity == FManaged
- [presentation code](https://github.com/indyscala/resources)

### May 1, 2017

- Brad Fritz -- [Introduction to Scala Type Classes](https://github.com/indyscala/typeclass-intro)
- Ross A. Baker -- []
