A month ago, I got my first job and became an intern developer, our team uses the Scala language. It seems to me that all novice developers are lost on the first day. at the same time, a lot of new names, technologies, some rules are piling up, and what else is not enough, absolutely everything is new for you, this is the first job. In my case, I also did not know the language in which I would program, until the time of the interview I had never even heard of it. Bottom line: the first day I was completely out of touch. Ask how I got this job then? I knew Java, at the interview I was told that it would be quite easy for a javist to switch to a rock and not worry. But apparently it was still worth a little bit to drink, because the first time in front of me I saw just screens filled with text, in which almost half was clear at once.
But even the fact that I didn’t understand something brought more discomfort, but the fact that there is 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";
val str = "abc"
This is how the function is described:
')
int sum(int a, int b) {return a+b;}
def sum(a: Int, b: Int) = {a + b}
And Scala has a REPL console (Read-eval-print-loop), as, for example, in Python. As you have already noticed, the semicolons are gone. You can run single-page programs without main'a, the names of methods and variables can contain and begin with any symbols at all, no rules. There is not static, but there is an Object, there are also primitives objects, == there are in fact equals. If the method has no parameters, then it is not necessary to put a period to call the method, brackets are optional if there are no parameters, and if it takes only 1 parameter, then you can write like this:
str.charAt(5);
str charAt 5
And one more interesting example:
val res = 1 + 1
No, it’s not just 1 plus 1, here object 1 calls method + and only object 1 is passed to it. For me, this was a pattern break.
To help my shock came a great book by David Pollack - Beginning Scala. The book begins with a single phrase, after which I realized that I must read it through to the end:
Ouch! That hurts my brain! Stop making me think differently. Oh, wait ... it hurts less now. I get it. Benefits. I felt that way. I felt like coding Scala.
David has a great programming experience, 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 it is not so easy to master him, it took him 2 years to do this, but he hopes that we can be faster and he will help with this. This is not a very simple book and it involves a certain amount of programming experience with the reader. Especially it will appeal to those who previously programmed in Java, because There are many references to this language and can be compared.
In addition to Beginning Scala, in parallel, I read Twitter's Scala School lessons, there is a Russian translation for all lessons, and David Pollack’s book was found only in the English version.
In addition to independent travels through the sources of the rock and work, Scala Exercises helped to fix the theory, 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 really correctly.
And I will tell a little about the most common and very simple things that I had to comprehend in the first place.
Option . In a nutshell, this is a container in which either is empty (None, it looks like null, but has methods map, filter, ...), or there is exactly one value Some (value) and its use can make the code more secure and not throwing a NullPointerException, because you don't want it, but you still need to extract the clean data from Option, and at that moment it is already difficult to forget to write a check.
Of course, Option has a get method, but using it is not recommended because in this case, the whole meaning of Option is lost, because None.get raises an exception.
Some of the most obvious amenities are:
Easy to return default value in case of empty Option
optValue.getOrElse(defaultValue)
In case of any actions:
optValue match { case Some(value) => action case None => defaultAction }
An example from Scala Beginning. The path is a certain database which contains records of types Person
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 was very concise.
Pattern matching . In the beginning, I thought that this is the same javovsky switch and I almost will not use it, but it is not. Scala is one of the most commonly used constructs.
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. Scala Beginning example
Stuff("David", 45) match { case Stuff("David", age) if age < 30 => "young David" case Stuff("David", _) => "old David" case _ => "Other" }
FunctionsTo begin with, in Scala, functions are instances that implement a specific interface, or rather, trait FunctionX, where X is the number of parameters and takes a value from 1 to 22. In this rub the only method, aplly, which is called for the function. Since functions are ordinary instances, we can transfer and return them from methods and functions.
An example from Scala Beginning. We pass some function from Int to String in the answer, and it returns the result of this function with parameter 42.
def answer(f: Function1[Int, String]) = f(42)
or what is the same
def answer(f: Function1[Int, String]) = f.apply(42)
Very handy thing functional combinators /
Leave only positive elements in the array:
arr.filter(value => value > 0)
A slightly more complicated example. Calculate the sum of the values of the function f from the positive elements of the list. 2 ways to do this:
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 did not want to teach anyone Scala or talk about the language as such, there are quite a lot of such articles on Habré and on the Internet, and many are very good and useful. My goal was just to tell my story, which may be interesting to someone and will be able to help and support some of the same lost newcomer, whom fate had just pushed with this rock. Good luck! I urge experienced programmers to share their comments and advice in the comments, at the expense of the novice Scala programmer.