This cheat sheet from here actually originated from the forum, credits to Laurent Poulain.We copied it and changed or added a few things.
- Scala implicitly converts the String to a RichString and invokes that method to get an instance of Regex. To find a first match of the regular expression, simply call the findFirstIn method. If instead of finding only the first occurrence we would like to find all occurrences of the matching word, we can use the findAllIn ( ) method and in.
- Scala Cheatsheet Thanks to Brendan O’Connor, this cheatsheet aims to be a quick reference of Scala syntactic constructions. Licensed by Brendan O’Connor under a CC-BY-SA 3.0 license.
- Scala provides “rich wrapper” around basic types via implicit conversions. Code Result 0 max 5 5 0 min 5 0-2.7 abs 2.7-2.7 round-3L 1.5 isInfinity false (1.0 / 0) isInfinity true 4 to 6 Range(4,5,6) 'nick' capitalize “Nick” 'nicolas' drop 2 “colas” Literals Integer val dec = 31 Decimal Integer val hex = 0XFF Hexa Integer.
Evaluation Rules
Since it's hard to search for scala syntactic constructions, hopefully this page might help. Note language coverage is incomplete. Source on github. Designed for scala 2.8 and 2.9. Portions adapted from A. Sundararajan's java vs. Scala cheat sheet: also check out. Cats Typeclass Cheat Sheet Adam Rosien (adam@rosien.net) October 14, 2017 Installation In your build.sbt file: libraryDependencies += 'org.typelevel'%% 'cats-core'% '1.0.0-MF' Then in your.scala files: import cats. Defining Signatures Each typeclass is defined by a particular function signature and a set.
- Call by value: evaluates the function arguments before calling the function
- Call by name: evaluates the function first, and then evaluates the arguments if need be
Higher order functions
These are functions that take a function as a parameter or return functions.
Currying
Converting a function with multiple arguments into a function with asingle argument that returns another function.
Classes
this
references the current object, assert(<condition>)
issues AssertionError
if conditionis not met. See scala.Predef
for require
, assume
and assert
.
Operators
myObject myMethod 1
is the same as calling myObject.myMethod(1)
Operator (i.e. function) names can be alphanumeric, symbolic (e.g. x1
, *
, +?%&
, vector_++
, counter_=
)
The precedence of an operator is determined by its first character, with the following increasing order of priority:
The associativity of an operator is determined by its last character: Right-associative if ending with :
, Left-associative otherwise.
Note that assignment operators have lowest precedence. (Read Scala Language Specification 2.9 sections 6.12.3, 6.12.4 for more info)
Class hierarchies
To create a runnable application in Scala:
or
Class Organization
Classes and objects are organized in packages (
package myPackage
).They can be referenced through import statements (
import myPackage.MyClass
,import myPackage._
,import myPackage.{MyClass1, MyClass2}
,import myPackage.{MyClass1 => A}
)They can also be directly referenced in the code with the fully qualified name (
new myPackage.MyClass1
)All members of packages
scala
andjava.lang
as well as all members of the objectscala.Predef
are automatically imported.- Traits are similar to Java interfaces, except they can have non-abstract members:
General object hierarchy:
scala.Any
base type of all types. Has methodshashCode
andtoString
that can be overriddenscala.AnyVal
base type of all primitive types. (scala.Double
,scala.Float
, etc.)scala.AnyRef
base type of all reference types. (alias ofjava.lang.Object
, supertype ofjava.lang.String
,scala.List
, any user-defined class)scala.Null
is a subtype of anyscala.AnyRef
(null
is the only instance of typeNull
), andscala.Nothing
is a subtype of any other type without any instance.
Type Parameters
Conceptually similar to C++ templates or Java generics. These can apply to classes, traits or functions.
It is possible to restrict the type being used, e.g.
Variance
Given A <: B
If C[A] <: C[B]
, C
is covariant
If C[A] >: C[B]
, C
is contravariant
Otherwise C is nonvariant
For a function, if A2 <: A1
and B1 <: B2
, then A1 => B1 <: A2 => B2
.
Functions must be contravariant in their argument types and covariant in their result types, e.g.
Scala Syntax Cheat Sheet
Find out more about variance inlecture 4.4and lecture 4.5
Pattern Matching
Pattern matching is used for decomposing data structures:
Here are a few example patterns
The last example shows that every pattern consists of sub-patterns: itonly matches lists with at least one element, where that element is apair. x
and y
are again patterns that could match only specifictypes.
Options
Pattern matching can also be used for Option
values. Somefunctions (like Map.get
) return a value of type Option[T]
whichis either a value of type Some[T]
or the value None
:
Most of the times when you write a pattern match on an option value,the same expression can be written more concisely using combinatormethods of the Option
class. For example, the function getMapValue
can be written as follows:
Pattern Matching in Anonymous Functions
Pattern matches are also used quite often in anonymous functions:
Instead of p => p match { case ... }
, you can simply write {case ...}
, so the above example becomes more concise:
Collections
Scala defines several collection classes:
Base Classes
Iterable
(collections you can iterate on)Seq
(ordered sequences)Map
(lookup data structure)
Immutable Collections
List
(linked list, provides fast sequential access)Stream
(same as List, except that the tail is evaluated only on demand)Vector
(array-like type, implemented as tree of blocks, provides fast random access)Range
(ordered sequence of integers with equal spacing)String
(Java type, implicitly converted to a character sequence, so you can treat every string like aSeq[Char]
)Map
(collection that maps keys to values)Set
(collection without duplicate elements)
Mutable Collections
Array
(Scala arrays are native JVM arrays at runtime, therefore they are very performant)- Scala also has mutable maps and sets; these should only be used if there are performance issues with immutable types
Examples
Pairs (similar for larger Tuples)
Ordering
There is already a class in the standard library that represents orderings: scala.math.Ordering[T]
which containscomparison functions such as lt()
and gt()
for standard types. Types with a single natural ordering should inherit from the trait scala.math.Ordered[T]
.
For-Comprehensions
A for-comprehension is syntactic sugar for map
, flatMap
and filter
operations on collections.
The general form is for (s) yield e
s
is a sequence of generators and filtersp <- e
is a generatorif f
is a filter- If there are several generators (equivalent of a nested loop), the last generator varies faster than the first
- You can use
{ s }
instead of( s )
if you want to use multiple lines without requiring semicolons e
is an element of the resulting collection
Example 1
is equivalent to
Translation Rules
A for-expression looks like a traditional for loop but works differently internally
for (x <- e1) yield e2
is translated to e1.map(x => e2)
for (x <- e1 if f) yield e2
is translated to for (x <- e1.filter(x => f)) yield e2
Scala Cheatsheet
for (x <- e1; y <- e2) yield e3
is translated to e1.flatMap(x => for (y <- e2) yield e3)
This means you can use a for-comprehension for your own type, as longas you define map
, flatMap
and filter
.
For more, see lecture 6.5.
Example 2
is equivalent to
is equivalent to
In this section, we will show small code snippets and answers to common questions. So let's get started!
ScalaTest:
Collection:
General:
Futures:
ScalaTest Introduction
ScalaTest is a popular framework within the Scala eco-system and it can help you easily test your Scala code. As per the official ScalaTest documentation, ScalaTest is simple for Unit Testing and, yet, flexible and powerful for advanced Test Driven Development.
ScalaTest provides various flavours to match your test style and in the examples below we will be using FlatSpec. You can find in-depth code snippets on assertions and matchers from the official ScalaTest FlatSpec documentation.
For additional details on the other test styles such as FunSpec, WordSpec, FreeSpec, PropSpec and FeatureSpec, please refer to the official ScalaTest documentation.
Add ScalaTest as dependency to build.sbt
In order to use ScalaTest, you will need to add the dependencies in your build.sbt file as shown below. If you are unsure about adding external libraries as dependencies to build.sbt, you can review our tutorial on SBT Depedencies.
Create a test class using FlatSpec and Matchers
Let's assume that we have a class called DonutStore and we would like to create a test class for it. Using ScalaTest, you can create a test class by extending org.scalatest.FlatSpec. In your test class, you would typically have a series of assertions, which we will show in the next tutorial. As such you can also add the trait org.scalatest.Matchers.
Equality Test
Assume we have a method named favouriteDonut() in a DonutStore class, which returns the String name of our favourite donut. We can create a test case for the favouriteDonut() method using ScalaTest's equality matchers as shown below.
In IntelliJ, to run our test class Tutorial_02_Equality_Test, simply right click on the test class and select Run Tutorial_02_Equality_Test.
If you are just getting started with ScalaTest, you can review the previous tutorials for adding ScalaTest dependency in your build.sbt, and extending the FlatSpec class with the Mathers trait.
Length Test
Throughout your program, you may be capturing list of items into Scala's Collection data structures. For instance, we'll go ahead and update our DonutStore class with a donuts() method, which will return an Immutable Sequence of type String representing donut items.
Using ScalaTest's length and size matchers, you can easily create tests for collection data types. As such, you can test that our donuts() method would always return a Sequence of type String whose length is equal to 3 donut items from the code snippet below.
To run your test class Tutorial_03_Length_Test in IntelliJ, simply rightclick on the test class and select Run Tutorial_03_Length_Test.
Boolean Test
In the previous example, we showed how to use ScalaTest's length and size matchers to write length tests such testing the number of elements in a collection. ScalaTest matchers also comes with handy , shouldEqual and should methods, which you can use to write boolean tests.
For instance, you may test that a certain element exists in a collection or a collection is not empty. The code below illustrates some of the Boolean tests using ScalaTest's matchers.
For the purpose of this boolean test, we are reusing the DonutStore class from the previous Length test:
Similar to the previous ScalaTest examples, rightclick on the test class Tutorial_04_Boolean_Test and select Run to run the test within IntelliJ.
Collection Test
So far, we've introduced ScalaTest Equality, Length and Boolean tests using ScalaTest's matchers. In this section, we'll present how you can use ScalaTest's matchers to write tests for collection types by using shouldcontain, shouldnotcontain or even shouldEqual methods.
As an example, the code below shows how to test that an element exists, or not, within a collection type (in our case, a donut Sequence of type String).
As a reminder, our DonutStore class for this Collection Test is similar to our previous examples as follows:
By now, you should be familiar how to run the test, by rightclicking on the test class Tutorial_05_Collection_Test and select the Run menu item within IntelliJ.
Type Test
Let's continue our journey into learning how to test your Scala classes by using the popular ScalaTest library. In this section, we'll present how you can use ScalaTest's should be a method to easily test certain types, such as a String, a particular collection or some other custom type.
We'll use our DonutStore example, and test that a DonutStore value should be of typeDonutStore, the favouriteDonut() method will return a Stringtype, and the donuts() method should be an Immutable Sequence.
Similar to our previous examples, the DonutStore class is as follows:
To run the Tutorial_06_Type_Test test class in IntelliJ, rightclick on the class name and select the Run menu item.
Exception Test
Throwing exceptions is generally a bad idea in programming, and even more so in Functional Programming. Exceptions break the flow of our program, and can lead to unexpected behaviour.
Nonetheless, as per our Scala Programming Introduction tutorial, we've seen that Scala is both an Object Oriented and Functional Programming language. For that reason, it is very likely that in a real-life Scala application (especially within a large enterprise codebase), you may be interfacing with some Object Oriented pattern or with a legacy Java library, which may be throwing exceptions.
As a result, we'll show how you can use ScalaTest to write tests versus knownexceptions. Let's go ahead and modify our DonutStore class with a dummy printName() method, which basically throws an IllegalStateException.
To catch the exception thrown by printName() method from the DonutStore class, you can use ScalaTest's intercept method:
If you need to verify the exception and its message, you can use a combination of ScalaTest's the() and thrownBy() methods:
In case you only need to test the exception message, you can use ScalaTest's the(), thrownBy() and should have message methods:
To write a test to verify only the type of the Exception being thrown, you can make use of ScalaTest an and should be thrownBy() methods:
Right click on the class Tutorial_07_Exception_Test and select the Run menu item to run the test within IntelliJ.
Private Method Test
If you are following a Functional Programming approach, it would be perhaps rare to test private methods. Instead, you would achieve similar behaviour by making use of say Partial Function, Partially Applied Functions or Higher Order Functions - to name a few.
However, as we've noted in the previous ScalaTest Exception Test tutorial, in a large enterprise code base, you will most certainly have to interface with legacy or Object Oriented libraries. In turn, these may require you to make use of testingprivatemethods in classes. With ScalaTest, you also have the ability to easily test private methods by making use of import org.scalatest.PrivateMethodTester._
Let's begin by adding two methods to our DonutStore class: a donutPrice() method which will return a price for a given donut, and a private discountByDonut() method which applies a certain discount for a given donut. We are keeping both methods fairly simple in order to focus on the testing of privatemethod using ScalaTest. Having said that, it is worth noting that the methods below do have codesmell by having internalstate and side effects!
As shown below, by simply importing org.scalatest.PrivateMethodTest._, you get access to an easy syntax for testing private methods using ScalaTest. In our example, we're testing the private method discountByDonut() for the input of vanilla donut.
To run the test code in IntelliJ, you can rightclick on the Tutorial_08_Private_Method_Test class and select the Run menu item.
Future Method Test
In Chapter 9 on Futures Tutorials, we showed how you can create asynchronousnon-blocking operations by making use of Scala Futures. But, what about testing asynchronous methods? Thanks to ScalaTest, that's pretty easy by importing the org.scalatest.concurrent.ScalaFutures trait.
Let's go ahead and add an asynchronous method named donutSalesTax(), which returns a future of type Double. The actual implementation of this method is redundant, as we're simply using a Thread.sleep(3000) to simulate a somewhat long-running operation. Instead, we'll focus on how to use ScalaTest to test this non-blocking method.
To this end, you will need to first import the org.scalatest.concurrent.ScalaFuturestrait, along with extending the usual FlatSpec class and importing the Matchers trait.
Next, you can provide your own PatienceConfig to determine the duration of the future operation. Finally, to test the future donutSalesTax() method, you can use the whenReady() method and pass-through the donutSalesTax() method as shown below.
In IntelliJ, rightclick on the Tutorial_09_Future_Test class and select the Run menu item to run the test code.
Convert Java collection to Scala collection
Add line break or separator for given platform
Convert multi-line string into single line
Check the value of an Option
Cannot find an implicit ExecutionContext
Read a file and return its contents as a String
Create enum using sealed trait
Int division in Scala and return a float which keeps the decimal part
NOTE: You have to be explicit and call .toFloat