Skip to content

Initial commit of the ‘Hello, Scala’ book contents #1423

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
wants to merge 1 commit into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions _data/doc-nav-header.yml
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,8 @@
url: "/tutorials/scala-for-java-programmers.html"
- title: Online Resources
url: "/learn.html"
- title: “Hello, Scala” Book
url: "/overviews/hello-scala/introduction.html"
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I would put this item higher on the menu. Just after the “Tour of Scala”, for instance. Also, I would remove the /overviews segment from the URL (just move the hello-scala directory to its grand-parent directory). “Overviews” are usually in the “Guides & Overviews” menu. (I know I’ve first suggested to put “Hello, Scala” in the overviews, but now I think it’s better to have it in the “Learn” menu).

Also, what do you think of just naming this item “Hello, Scala”? I don’t think we should have the “Book” suffix at least.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yes, I can move the link higher. I thought there might be some discussion about where to put it, so I started with it at the bottom.

I’ll also move the hello-scala directory up.

I added the “Book” part because I thought “Hello, Scala” in the menu looked a little strange on its own. I couldn’t think of a better way to show that this is a book. But I’ll remove it, and also remove the quotes around the Hello, Scala title.

Copy link
Contributor Author

@alvinj alvinj Jul 9, 2019

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@julienrf I may have misread what you wrote. Are you going to change the “multipage-overview” layout formatting, or should I use the “tour” layout? Thanks! (Or if you want I can see if I can figure out the “multipage-overview” layout.)

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@julienrf I can also remove the Akka lessons, and put a link to the Akka website at the end of the Futures lesson.

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Are you going to change the “multipage-overview” layout formatting, or should I use the “tour” layout?

Actually, I’m not sure! My reasoning was that anyway having working “next page”/“previous page” and current page highlight in the TOC would be beneficial to other multipage overviews, so we should anyway improve that layout. I’m not sure we can easily reuse the “tour” layout without breaking things because it has been designed specifically for the Tour.

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think that the “multipage-overview” layout doesn’t work when the hello-scala directory is directly under the root directory. I’m pretty sure that’s the case, but I could be wrong.

Haha, that’s the joy of working with an untyped system 😂

Then I suggest that you leave everything under the overview/ directory, and focus on the content of the guide.

my initial thought was to create a new “book” layout, but it sounds like we all want next/previous links and a TOC that highlights the current page

That’s what I think too. I will take some time to improve the “multipage-overview” layout so that the current page is highlighted in the TOC, and we can have links between pages.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Okay, sounds good, I’ll work on the content. Thanks again!

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@alvinj I’ve just created #1437 for highlighting the current page in the TOC of a multipage overview. I’m about to work on the “next”/“previous” links, but do I understand that you already did that work?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

No, I ended up not doing anything there. (When I used the Tour layout, the next/previous links worked, but everything stopped working when I moved the book content to the root directory, so I never tried to integrate that into the multipage-overview.)

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

OK, I’ve created #1440 to support links between pages of an overview.

- title: Reference
url: "#"
submenu:
Expand Down
19 changes: 19 additions & 0 deletions _overviews/hello-scala/about.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
---
layout: multipage-overview
title: About This Book
description: About the book, 'Hello, Scala'
partof: hello_scala
overview-name: Hello, Scala
num: 59
outof: 59
---

Here are a few notes to wrap up the book:

*Hello, Scala* was originally created by [Alvin Alexander](https://alvinalexander.com), author of the *Scala Cookbook* and *Functional Programming, Simplified*. Over time this document will be updated by the Scala community.

If you prefer reading printed books, you can [buy “Hello, Scala” on Amazon.com](https://www.amazon.com/Hello-Scala-Alvin-Alexander/dp/1720790027/).

And finally a bit of gratitude on my behalf: Many thanks to the creators of [the Scala programming language](https://www.scala-lang.org) for creating such a wonderful language.


116 changes: 116 additions & 0 deletions _overviews/hello-scala/abstract-classes.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,116 @@
---
layout: multipage-overview
title: Abstract Classes
description: This page shows how to use abstract classes, including when and why you should use abstract classes.
partof: hello_scala
overview-name: Hello, Scala
num: 27
---



Scala also has a concept of an abstract class that is similar to Java’s abstract class. But because traits are so powerful, you rarely need to use an abstract class. In fact, you only need to use an abstract class when:

- You want to create a base class that requires constructor arguments
- Your Scala code will be called from Java code



## Scala traits don’t allow constructor parameters

Regarding the first reason, Scala traits don’t allow constructor parameters:

```scala
// this won't compile
trait Animal(name: String)
```

Therefore, you need to use an abstract class whenever a base behavior must have constructor parameters:

```scala
abstract class Animal(name: String)
```

However, be aware that a class can extend only one abstract class.



## When Scala code will be called from Java code

Regarding the second point — the second time when you’ll need to use an abstract class — because Java doesn’t know anything about Scala traits, if you want to call your Scala code from Java code, you’ll need to use an abstract class rather than a trait.

I won’t show how to do this in this book, but if you’re interested in an example, please see the *Scala Cookbook*.



## Abstract class syntax

The abstract class syntax is similar to the trait syntax. For example, here’s an abstract class named `Pet` that’s similar to the `Pet` trait I defined in the previous lesson:

```scala
abstract class Pet (name: String) {
def speak(): Unit = { println("Yo") } // concrete implementation
def comeToMaster(): Unit // abstract method
}
```

Given that abstract `Pet` class, you can define a `Dog` class like this:

```scala
class Dog(name: String) extends Pet(name) {
override def speak() = println("Woof")
def comeToMaster() = println("Here I come!")
}
```

The REPL shows that this all works as advertised:

```scala
scala> val d = new Dog("Rover")
d: Dog = Dog@51f1fe1c

scala> d.speak
Woof

scala> d.comeToMaster
Here I come!
```

### Notice how `name` was passed along

All of that code is similar to Java, so I won’t explain it in detail. One thing to notice is how the `name` constructor parameter is passed from the `Dog` class constructor to the `Pet` constructor:

```scala
class Dog(name: String) extends Pet(name) {
```

Remember that `Pet` is declared to take `name` as a constructor parameter:

```scala
abstract class Pet (name: String) { ...
```

Therefore, this example shows how to pass the constructor parameter from the `Dog` class to the `Pet` abstract class. You can verify that this works with this code:

```scala
abstract class Pet (name: String) {
def speak { println(s"My name is $name") }
}

class Dog(name: String) extends Pet(name)

val d = new Dog("Fido")
d.speak
```

I encourage you to copy and paste that code into the REPL to be sure that it works as expected.










114 changes: 114 additions & 0 deletions _overviews/hello-scala/akka-actors-101.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,114 @@
---
layout: multipage-overview
title: Akka Actors
description: This page provides an introduction to Akka Actors, specifically how to use actors in Scala.
partof: hello_scala
overview-name: Hello, Scala
num: 55
---

In this lesson I provide a brief introduction to the [Akka actors library](http://akka.io/). In the lesson you’ll learn about:

- Actors and the actor model
- Akka’s benefits

At the end I also share a link to a video of an Alexa-like application I wrote using actors

>If you’re already comfortable with the *Actor model*, feel free to move on to the next lesson, where I share some Scala/Akka code.



## Actors and the Actor Model

The first thing to know about actors is the *actor model*, which is a mental model of how to think about a system built with actors. Within that model the first concept to understand is an *actor*:

- An actor is a long-running process that runs in parallel to the main application thread, and responds to messages that are sent to it.
- An actor is the smallest unit of functionality when building an actor-based system, just like a class is the smallest unit in an OOP system.
- Like a class, an actor encapsulates state and behavior.
- You can’t peek inside an actor to get its state. You can send an actor a message requesting state information (like texting a person to ask how they’re feeling), but you can’t reach in and execute one of its methods or access its fields (just like you can’t peak inside someone else’s brain).
- An actor has a mailbox (an inbox), and the actor’s purpose in life is to process the messages in its mailbox.
- You communicate with an actor by sending it an immutable message (typically as a case class or case object in Akka). These messages go directly into the actor’s mailbox.
- When an actor receives a message, it’s like taking a letter out of its mailbox. It opens the letter, processes the message using one of its algorithms, then moves on to the next message in the mailbox. If there are no more messages, the actor waits until it receives one.

Akka experts recommend thinking of an actor as being like a person, such as a person in a business organization:

- You can’t know what’s going on inside another person. All you can do is send them a message and wait for their response.
- An actor has one parent, known as a *supervisor*. In Akka, that supervisor is the actor that created it.
- An actor may have children. For instance, a President in a business may have a number of Vice Presidents. Those VPs are like children of the President, and they may also have many subordinates. (And those subordinates may have many subordinates, etc.)
- An actor may have siblings — i.e., other actors at the same level. For instance, there may be 10 VPs in an organization, and they are all at the same level in the organization chart.


### Actors should delegate their work

There’s one more important point to know about actors: As soon as a top-level actor receives a message, it should delegate its work. Actors need to be able to respond to messages in their mailbox as fast as possible, so the actor mantra is, “Delegate, delegate, delegate.”

If you think of an actor as being a person, imagine that one message includes a task that’s going to take a month to complete. If the actor worked on that task for a month, it wouldn’t be able to respond to its mailbox for a month. That’s bad. But if the actor delegates that task to one of its children, it can respond to the next message in its mailbox immediately (and delegate that as well).



## Akka features

Akka is the main actor library for Scala, and it’s a great way to build massively parallel systems. From my own experience I can say that all of these industry buzzwords can be used to describe Akka:

- asynchronous
- event-driven
- message-driven
- reactive
- scalable (“scale up” and “scale out”)
- concurrent and parallel
- non-blocking
- location transparency
- resilient and redundant (no single point of failure with multiple, distributed servers)
- fault-tolerant

All of those features are great, but the first great feature is that Akka and the actor model *greatly* simplify the process of working with long-running threads. In fact, when working with Akka, you never really think about threads, you just write actors to respond to messages in a non-blocking manner, and the threads take of themselves.


## Akka benefits

In addition to those features, here are some concrete benefits of using Akka actors, mostly coming from Lightbend’s [Akka Quickstart Guide](http://developer.lightbend.com/guides/akka-quickstart-scala/) and [the Akka.io website](http://akka.io):

- Actors are *much* easier to work with than threads; you program at a much higher level of abstraction.
- Actors let you build systems that *scale up*, using the resources of a server more efficiently, and *scale out*, using multiple servers.
- Performance: Actors have been shown to process up to 50 million messages/second on a single machine.
- Lightweight: Each instance consumes only a few hundred bytes, which allows millions of concurrent actors to exist in a single application (allowing ~2.5 million actors per GB of heap).
- Location transparency: The Akka system constructs actors from a factory and returns references to the instances. Because the location of actors doesn’t matter — they can be running on the current server or some other server — actor instances can start, stop, move, and restart to scale up and down, as well as recover from unexpected failures.



## A video example

Way back in 2011 I started developing a “personal assistant” named [SARAH](http://alvinalexander.com/sarah), which was based on the computer assistant of the same name on the television show [Eureka](http://www.imdb.com/title/tt0796264/). SARAH is like having the Amazon Echo running on your computer. You speak to it to access and manage information:

- Get news headlines from different sources
- Get weather reports and stock prices
- Manage a “to-do list”
- Control iTunes with voice commands
- Check your email
- Perform Google searches

Beyond just *responding* to voice commands with spoken and displayed output, SARAH also has long-running background tasks — small pieces of software I call “agents” — so it can do other things:

- Tell me when I receive new email from people I’m interested in
- Report the time at the top of every hour (“The time is 11 a.m.”)

The entire application is based on Akka actors. I found Akka to be a terrific way to write an application that had many threads running simultaneously.

For more information on SARAH, see the “Sarah - Version 2” video at [alvinalexander.com/sarah](https://alvinalexander.com/sarah). I haven’t worked on SARAH in a while, but it gives you can idea of what can be done with Akka actors.

>For a simpler version of SARAH that you can get started with today, see my tutorial, [“Alexa written with Akka” = Aleka](https://alvinalexander.com/scala/alexa-plus-akka-equals-aleka-tutorial)



## What’s next

Given this background, the next lesson shows several examples of how to use Akka actors.

>From [the Akka FAQ](https://doc.akka.io/docs/akka/2.5/additional/faq.html), the name *Akka* “is the name of a beautiful Swedish mountain in the northern part of Sweden called Laponia ... Akka is also the name of a goddess in the Sámi (the native Swedish population) mythology. She is the goddess that stands for all the beauty and good in the world ... Also, the name AKKA is a palindrome of the letters A and K, as in Actor Kernel.”







Loading