Git Product home page Git Product logo

intro-to-scala's Introduction

Intro to Scala Fundamentals

Build Status

This is a two day course. You are expected to know how to program in at least one programming language (Java, Ruby, JavaScript, etc.). The course teaches the fundamentals of using Scala as a functional programming language.

This course is meant to be run in person. There are comments in the exercises to try and point you in the right direction so you should be able to do this in your spare time if you desire. Unit tests are included to verify your solutions for each exercise.

Use ./auto/sbt test to run the tests. The first time you run the tests, they will all fail. This is a good thing! As you complete each exercise correctly, the tests will pass.

We welcome pull requests and feedback!

Schedule

Day 1

Time Topic/Exercise
09.00 Start
09.15 Intro to FP/Scala
10.00 IntroExercises
10.45 Morning break
11.00 Intro to ADTs
11.15 TypesExercises
12.15 Lunch
13.30 ListExercises
15.15 Afternoon break
15.30 NullExercises
16.00 OptionExercises pt. 1 (Safe constructors)
16.30 OptionExercises pt. 2 (first half)
17.00 End

Day 2

Time Topic/Exercise
09.15 Intro to Error Handling
10.00 OptionExercises pt. 2 (second half)
10.30 Morning break
10.45 OptionExercises pt. 3
11.30 ExceptionExercises
12.15 Lunch
13.15 Exceptions2EitherExercises
14.30 TryExercises
15.00 Afternoon break
15.30 LogParser
16.45 Wrap up
17.00 End

Pre-requisites

At a minimum, you need:

  • This repository
  • Java 17 installed (even if you have a newer version)
  • Docker
  • Text editor (IntelliJ is recommended)

1. Fork or clone this repository

$ git clone https://github.com/wjlow/intro-to-scala.git
$ cd intro-to-scala/

2. Install Java 17 (even if you already have a later version pre-installed)

Test if you have Java 17 already with java -version.

macOS (using Homebrew)

Run the following two commands:

brew install openjdk@17

3. Install Docker

macOS

Use Docker for Mac

4. Run SBT through Docker

To run the sbt shell using Docker:

$ ./auto/sbt

Tip: Launching SBT might take some time, so we recommend using SBT's interactive shell to run commands, instead of lauching SBT for each command.

Compilation

Launch the SBT shell.

To only compile production code use:

sbt> compile

To compile production and test code use:

sbt> test:compile

How to run tests

To run all tests

To run all tests use:

sbt> test

The first time you run all the tests you will get a lot of errors! These tests will be fixed by you during the duration of the course.

Running a single test file

In the meantime, run only a single test case at a time to keep things manageable.

To run a single test, use:

sbt> ~testOnly package.path.of.test.TestName

For example, to run only the introcourse.level01.IntroExercisesTest test case, use:

sbt> ~testOnly introcourse.level01.IntroExercisesTest

To run by test case name only, use:

sbt> ~testOnly *TestName

For example, to run the introcourse.level01.IntroExercisesTest test case, use:

sbt> ~testOnly *IntroExercisesTest

The ~ watches for changes to your files and runs the command automatically. It's nice to use it to get really fast feedback as you are working on the exercises!

To stop watching changes through ~, press Enter to return to the SBT shell prompt.

Jumping into a Scala REPL

To launch into a Scala REPL with all production code use:

sbt> console

Once in the console, you can import your production code as such:

import package.objectname.*

For example, to use functions defined in introcourse.level01.IntroExercises:

scala> import introcourse.level01.IntroExercises.*
scala> add(1, 2)
res0: Int = 3

To launch into a Scala REPL with all production and test code use:

sbt> test:console

Type :q to exit from the REPL and return to SBT.

Exiting SBT

To exit the SBT shell use:

sbt> exit

IDE setup

IntelliJ IDEA (recommended)

intellij

  1. Download IntelliJ (free Community edition is fine)

  2. Install and open IntelliJ

  3. If running IntelliJ for the very first time, it might ask you what "featured" plugin you want to install. Select Install for Scala, otherwise install manually: Configure -> Plugins -> Browse Repositories -> Scala

  4. Restart IntelliJ to activate the plugin

  5. Open IntelliJ and open this project: Open -> Select directory where project is in

  6. IntelliJ will detect this as an SBT project. Select Import SBT Project when prompted

  7. In the pop-up, choose SDK -> JDK -> Java 17. If Java 17 is not available, add it by selecting New... to the right of Project JDK, then +JDK, then /Library/Java/JavaVirtualMachines/adoptopenjdk-17.jdk and finally Open

  8. Wait for IntelliJ to refresh the project and download dependencies (this might take a while)

  9. Build the project with Cmd + F9. If you get no errors, IntelliJ setup is all done!

Tips:

  • You can run individual tests by right-clicking and then selecting Run ...ExercisesTest (or just use SBT)

  • Use Cmd + P inside the argument of a function to see what type the argument needs to be.

  • Use Ctrl + Shift + P to find out the type of a highlighted expression.

Text Editor (Vim/Sublime/Atom/Emacs)

text editor

  1. Open the current directory in an editor of your choice.

  2. Open the SBT shell in a terminal window.

  3. Compiling - See SBT instructions on how to compile code.

  4. Running Tests - See SBT instructions on how to run tests.

  5. Looking up Scala API - You can also search through the Scala APIs to find any necessary methods or use a documentation browser like Dash.

  6. To explore the Scala API or any of the exercises use the Scala REPL - See SBT instructions on how to jump into the REPL.

scala api browser

Further documentation

intro-to-scala's People

Contributors

ashokkumar avatar benhutchison avatar chanjk avatar felipeeflores avatar frediy avatar george-wilson-rea avatar hanmoi-choi avatar lukestephenson avatar lukestephenson-zendesk avatar ninth-dev avatar ntdesilv avatar petern-sc avatar sanjivsahayamrea avatar shaun-whitely avatar ssanj avatar stefan-vrecic-pro avatar stilianouly avatar tcao-rea avatar tomcjohn avatar trammel avatar ttcao avatar void-kuangyi avatar wjlow avatar wsutina avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

intro-to-scala's Issues

Calculating `min` is weird.

In reality I would use NonEmptyList.from(list) and then reduce on the NEL.

But here people have to fold on the tail and it feels so odd.

Maybe we can rewrite this into an exercise where we concatenate a bunch of strings together?

Or to reverse a list?

Deprioritise zip exercises.

I think zipping isn't very important in this course. If we de-prioritise it (put it in the bonus section), we can bump getNames, getAdults and reverseList, which are exercises to rewrite imperative code in a functional way. I ran this recently and found that it was valuable.

Or we could introduce collect here to prepare students for Exception and Either exercises.

Upgrade to Scala 2.13

Will help in simplifying type signatures of collections

Depends on Delight and ScalaTest to be upgraded first

Add more exercises to Day 1.

I think we need to add at least 1 hard exercise to Types and List.

Some things we could consider adding:

  • Tuples (Intro)
  • Creating your own case class (Types)

ExceptionExercisesTest

For the createPerson function the assertions need to be fixed for the tests:

  • "should return Person if supplied a valid name and age"
    The test should assert Person("Fred", 32)

  • "should throw an EmptyNameException if the name supplied is empty"
    The test should assert "provided name is empty"

  • "should throw an InvalidAgeValueException if the age supplied is not an Int"
    The test should assert InvalidAgeValueException is thrown instead of InvalidAgeRangeException

Flashing with Frequency in TypeExercises

Adding a Flashing with a frequency to TypeExercises makes this a little too complex as:

  • We need to explain Regex matching or
  • Explain splitting and matching on Array.

If we get rid of the frequency this exercise will be much easier and we can easily demonstrate the compile-checked exhaustiveness.

  /**
    * We have a new traffic light called Flashing, with a frequency, e.g. "flashing 20", "flashing 100"
    *
    * Extend `showTrafficLightStr` that you have just implemented above to support this new functionality.
    *
    * Use a test driven approach to implement this new functionality.
    *
    * scala> showTrafficLightStr("flashing 20")
    * = "The traffic light is flashing with a frequency of 20"
    *
    * scala> showTrafficLightStr("flashing 100")
    * = "The traffic light is flashing with a frequency of 100"
    *
    * Hint: Use flashing regex and pattern matching or 
    * use `.split(" ")` and pattern-match on `Array("flashing", frequency)`
    **/

  val flashing = """^flashing\s(\d+)$""".r

Add more examples to Option1Exercises.mkTrafficLightThenShow

This:

  /**
    * scala> mkTrafficLightThenShow("red")
    * = "Traffic light is red"
    *
    * scala> mkTrafficLightThenShow("bob")
    * = "Traffic light `bob` is invalid"
    *
    * Hint: Use `mkTrafficLight` and pattern matching.
    *
    * You can pattern match on `Option` using its two constructors `Some` and `None`:
    *
    * ```
    * optSomething match {
    *   case Some(a) => // do something with `a`
    *   case None => // do something else
    * }
    * ```
    */
  def mkTrafficLightThenShow(str: String): String = ???

should change to:

  /**
    * scala> mkTrafficLightThenShow("red")
    * = "Traffic light is red"
    *
    * scala> mkTrafficLightThenShow("yellow")
    * = "Traffic light is yellow"
    *
    * scala> mkTrafficLightThenShow("green")
    * = "Traffic light is green"
    *
    * scala> mkTrafficLightThenShow("bob")
    * = "Traffic light `bob` is invalid"
    *
    * Hint: Use `mkTrafficLight` and pattern matching.
    *
    * You can pattern match on `Option` using its two constructors `Some` and `None`:
    *
    * ```
    * optSomething match {
    *   case Some(a) => // do something with `a`
    *   case None => // do something else
    * }
    * ```
    */
  def mkTrafficLightThenShow(str: String): String = ???

Add more examples to Option1Exercises.mkTrafficLight

  /**
    * scala> mkTrafficLight("red")
    * = Some(Red)
    *
    * scala> mkTrafficLight("bob")
    * = None
    **/
  def mkTrafficLight(str: String): Option[TrafficLight] = ???

should also have:

  /**
    * scala> mkTrafficLight("red")
    * = Some(Red)
    *
    * scala> mkTrafficLight("green")
    * = Some(Green)
    *
    * scala> mkTrafficLight("yellow")
    * = Some(Yellow)
    *
    * scala> mkTrafficLight("bob")
    * = None
    **/
  def mkTrafficLight(str: String): Option[TrafficLight] = ???

Do we need Wallet in TypeExercises?

We cover most of what Wallet does in TypeExercises with Person. Do we need to double up?

 //Type -> String
  def showWallet(wallet: Wallet): String = ???

is the same as:

def showPerson1(person: Person): String 
def showPerson2(person: Person): String 
 //immutable copy
  def purchase(cost: Double, wallet: Wallet): Wallet = ???

is the same as:

 def changeName(newName: String, person: Person): Person = ???

Introduce `flatMap` in `OptionExcercises2`

should we introduce flatMap on findJobIdByHumanId.

At this point people understand what an Option type is and how/when to use it. findJobIdByHumanId is a very good example of how you combine two Options. The IDE suggest that you should use flatMap instead of map.flatten.

The next exercise findJobByHumanId has the same intuition. We could introduce it here to show the difference.

Exceptions2EitherExercises does not need an hour fifteen

I think I can complete the Exceptions2EitherExercises in 45 mins similar to the ExceptionsExercises. The content of Exceptions2EitherExercises is very similar to ExceptionsExercises so there is much less overhead in going from one to the other - only translating Exceptions -> Eithers.

This should free up 30 mins which we can use somewhere else; maybe on the
TryExercises or LogParser?

Remove mkTrafficLightOrNull exercises from NullExercises

Remove mkTrafficLightOrNull exercises from NullExercises:

def mkTrafficLightOrNull(str: String): TrafficLight = ???
def mkTrafficLightOrNullThenShow(str: String): String = ???

as these are covered by the Person exercises:

def mkPersonOrNull(name: String, age: Int): Person = ???
def mkPersonOrNullThenChangeName(oldName: String, age: Int, newName: String): Person = ???

TyperExercises.showTrafficLightStr extension

To support the extension of TyperExercises.showTrafficLightStr:

We have a new traffic light called Flashing, with a frequency, e.g. "flashing 20", "flashing 100"

Extend showTrafficLightStr that you have just implemented above to support this new functionality.

should we mention:

Hint: String.split and pattern match on Array

or were you thinking of introducing regexs here?

"""flashing\s\(d+)""".r

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.