How I taught Scala

A month ago, I got my first job and became a trainee developer, our team uses the Scala language. It seems to me that all novice developers on the first day are lost. at the same time heaps of a bunch of new names, technologies, some rules, and you never know what, absolutely everything is new to you, this is the first work. In my case, I still did not know the language in which I would program, until the interview I had never even heard of it. Bottom line: on the first day I was in full out. Ask how then did I get this job? I knew Java, at the interview I was told that the javista will be able to go to the rock quite easily and you can not worry. But apparently a little bit ahead was still worth it, because the first time in front of me I just saw screens filled with text, in which almost half was immediately clear.

But even the fact that I didn’t understand something brought it more discomfort, but the fact that there was a lot different, and even the type of the variable comes after the name, and sometimes it doesn’t exist at all.

final String str = "abc"; //Java

val str = "abc" // Scala

This is how the function is described:

int sum(int a, int b) {return a+b;} // Java

def sum(a: Int, b: Int) = {a + b} // Scala

And Scala also has a console REPL (Read-eval-print-loop), as, for example, in Python. As you already noticed, the semicolons are missing. You can run single-page programs without a main, the names of methods and variables can contain and start with any characters at all, no rules. There is not static, but there is Object, there are also primitives objects, == there are actually equals. If the method has no parameters, then it is not necessary to put an end to the method call, the brackets are also optional if there are no parameters, and if it takes only 1 parameter, then you can write like this:

str.charAt(5); // Java

str charAt 5 // Scala

And another interesting example:

val res = 1 + 1

No, it's not just 1 plus 1, here the object 1, the + method is called and object 1 is passed to it as the only parameter. For me, this was a template break.

To my shock came a wonderful book by David Pollack - Beginning Scala. The book begins with one phrase, after which I realized that I must read it to the end:
Ouch! That hurts my brain! Stop making me think differently. Oh, wait ... it hurts less now. I get it. This different way of solving the problem has some benefits. I felt that way after my first year of law school. I felt that way for a while when I began coding Scala.
David has tremendous experience in programming, he started this business 20 years before my birth, managed to work with more than 10 programming languages, until he came to Scala. And now he says:
Scala is a programming language that provides a best-of-all-worlds experience for developers.
Nevertheless, the author honestly warns that mastering it is not so easy, it took him 2 years to do this, but he hopes that we can faster and he will help in this. This is not a very simple book and it involves some experience in programming with the reader. Especially those who previously programmed in Java will like it, because there are many references to this language and can be compared.

In addition to Beginning Scala, I also read Twitter's Scala School lessons, for all the lessons there is a translation into Russian, but David Pollack’s book was found only in the English version.

The Scala Exercises project helped to consolidate the theory in addition to independent travels through the source of rock and work, there are very simple tasks, but they are quite suitable for fixing some aspect at first and checking that you carefully read and understood everything correctly.

And I’ll tell you a little about the most common and very simple things that I had to comprehend in the first place.

The Option . In a nutshell - this is a container in which is either empty (None, it looks like null, but has map, filter, ...) methods, or there is some exactly one value Some (value) and its use can make the code more secure and not throwing a NullPointerException, because you want to, you don’t want to, but you still need to retrieve the clean data from Option, and at this point it is already difficult to forget to write a check.
Of course, Option has a get method, but it is not recommended to use it because in this case the whole point of Option is lost, because None.get throws an exception.
Some of the most obvious amenities:

It's easy to return the default value if Option is empty

optValue.getOrElse(defaultValue)

In case of any action:

optValue match {
      case Some(value) => action
      case None => defaultAction
}

Example from Scala Beginning. The path is a certain database that contains Person types

def findPerson(key: Int): Option[Person]

The method will return Some [Person] if such an entry is found and None otherwise.
Now we want to get the user's age by key.

def ageFromKey(key: Int): Option[Int] = findPerson(key).map(_.age)

We did not have to test for None and the method turned out to be very concise.

Pattern matching . At the beginning, I thought that this is the same Java switch and I will hardly use it, but it is not. In Scala, this is one of the most commonly used designs.

Cast:


obj match {
      case str: String => str
      case number: Int => number
}

You can add additional conditions and add a default action.


obj match {
      case strWithA: String if strWithA.contains("a") => strWithA
      case negative: Int if negative < 0 => negative
      case zero if zero == 0 => zero
      case _ => defaultAction
}

It is extremely convenient to use pattern-matching with case classes. Example from Scala Beginning


Stuff("David", 45) match {
      case Stuff("David", age) if age < 30 => "young David" 
      case Stuff("David", _) => "old David"
      case _ => "Other"
}

Functions

To begin with, in Scala, functions are instances that implement a certain interface, or rather trait FunctionX, where X is the number of parameters and takes a value from 1 to 22. In this tray, the only method is aplly, which is called for the function. Since functions are ordinary instances, we can pass and return them from methods and functions.
Example from Scala Beginning. We pass in a response some function from Int to String, and it returns the result of this function with parameter 42.


def answer(f: Function1[Int, String]) = f(42)

or the same thing


def answer(f: Function1[Int, String]) = f.apply(42)

A very convenient thing is functional combinators /

Leave only positive elements in the array:


arr.filter(value => value > 0)

A slightly more complex example. Calculate the sum of the values ​​of f from the positive elements of the list. 2 ways to do it:


list.filter(x => x > 0).foldLeft(0)(_ + f(_))
list.filter(x => x > 0).map(f).sum

And in the end I would like to say why I wrote all this at all. I didn’t want to teach anyone Scala or talk about the language as such, there are a lot of such articles on the Habré and on the Internet, and many are very good and useful. My goal was simply to tell my story, which might be interesting to someone and could help and support some of the same lost newcomer, whom fate had just collided with this rock. Good luck! Experienced programmers are encouraged to share their tips and opinions in the comments, regarding the path of a novice Scala programmer.

Also popular now: