Welcome to the Scala Tutorials. Scala is a modern multi-paradigm programming language designed to express common programming patterns in a concise, elegant, and type-safe way. Scala has been created by Martin Odersky and he released the first version in 2003
In addition to free Scala Tutorials, you can find interview questions, how to tutorials and issues and their resolutions of Scala.
Introduction
Scala is a programming language for general software applications. The design of Scala started in 2001, and the first public release was in 2004. The name Scala is a combination of the words “Scalable” and “Language,” which was chosen to indicate its design goal of growing with the demands of the user base. Many of the design decisions of Scala are inspired by perceived shortcomings of the Java language with Scala source code compiling to Java Byte Code, allowing it to run on a Java virtual machine. One of the biggest attractions of Scala is that it has full support for functional programming and has a very strong static type system. This allows for very concise code, requiring fewer lines of code to achieve the same functionality than many other languages, including Java.
Scala Features
Scala is both functional and object-oriented
- every value is an object
- every function is a value--including methods
Scala is statically typed
-includes a local type inference system:
in Java 1.5: Pair p = new Pair<Integer, String>(1, "Scala");
in Scala:val p = new MyPair(1, "scala");
Supports lightweight syntax for anonymous functions, higher-order functions, nested functions, currying
ML-style pattern matching
Integration with XML
-Can write XML directly in Scala program
-Can convert XML DTD into Scala class definitions
Support for regular expression patterns
Allows defining new control structures without using macros, and while maintaining static typing
Any function can be used as an infix or postfix operator
Can define methods named +, <= or ::
Scala object system
-Class-based
-Single inheritance
-Can define singleton objects easily
-Subtyping is nominal
-Traits, compound types, and views allow for more flexibility
Scala Operators
An operator is a symbol that tells the compiler to perform specific mathematical or logical manipulations. Scala is rich in built-in operators and provides following type of operators:
-Relational Operators
-Logical Operators
-Bitwise Operators
-Assignment Operators
Scala Collections
Collections are containers of things. Those containers can be sequenced, linear sets of items like List, Tuple, Option, Map, etc. The collections may have an arbitrary number of elements or be bounded to zero or one element (e.g., Option).
Basic Data Structures
-Lists
-Sets
-Tuple
-Maps
-Option
Functional Combinators
-map
-foreach
-filter
-zip
-partition
-find
-drop and dropWhile
-foldRight and foldLeft
-flatten
-flatMap
-Generalized functional combinators
-Map
Scala Data Types
Data Type | Description |
---|---|
Byte | 8 bit signed value. Range from -128 to 127 |
Short | 16 bit signed value. Range -32768 to 32767 |
Int | 32 bit signed value. Range -2147483648 to 2147483647 |
Long | 64 bit signed value. -9223372036854775808 to 9223372036854775807 |
Float | 32 bit IEEE 754 single-precision float |
Double | 64 bit IEEE 754 double-precision float |
Char | 16 bit unsigned Unicode character. Range from U+0000 to U+FFFF |
String | A sequence of Chars |
Boolean | Either the literal true or the literal false |
Unit | Corresponds to no value |
Null | null or empty reference |
Nothing | The subtype of every other type; includes no values |
Any | The supertype of any type; any object is of type Any |
AnyRef | The supertype of any reference type |
Scala Configuration
The separation of configuration from code is a good practice that makes our system customisable as we can load different configurations according to the environment we are running it in. In this article we will describe different approaches to load configurations in Scala and how they can be combined together: loading configurations from a file, from command line parameters or from environment variables.
Configurations from a file
Let’s start with the basic case scenario: given a file, we want to read it and parse its values to use them in our code.
First, we need to define our configuration file, let’s call itapplication.conf.
// application.conf
my {
secret {
value
=
"super-secret"
}
}
// config-tutorial.scala
import
com.typesafe.config.ConfigFactory
val
value
=
ConfigFactory.load().getString(
"my.secret.value"
)
println(s
"My secret value is $value"
)
Configurations from command line parameters
Another approach is to allow our users to redefine settings through command line parameters rather than changing the configuration file directly. All we have to do is changing our configuration file as following:
// application.conf
my {
secret {
value
=
"super-secret"
value
=
${?VALUE}
}
}
>> scala config-tutorial.scala
My secret value is
super
-secret
>> scala config-tutorial.scala -Dmy.secret.value
=
another-secret
My secret value is another-secret
Configurations from environment variables
Redefining configurations as part of the command line parameters works in most of the cases, but it can be tedious when we have a lot of parameters to change. Also putting sensitive information, such as passwords or tokens, in clear text in a configuration file or a run script may not be safe enough. Another option to load configurations is to inject our parameters from predefined environment variables.
In order to achieve this, we can just write a simple method that looks for a specific environment variable before loading the configurations in the previously described approach.
import
scala.util.Properties
def
envOrElseConfig(name
:
String)
:
String
=
{
Properties.envOrElse(
name.toUpperCase.replaceAll(
""
"\."
""
,
"_"
),
config.getString(name)
)
}
Interested in mastering Scala?Check out this blog post to learn more Scala Tutorials.
/ application.conf
my {
secret {
value
=
"super-secret"
value
=
${?VALUE}
}
}
import
com.typesafe.config.ConfigFactory
import
scala.util.Properties
class
MyConfig(fileNameOption
:
Option[String]
=
None) {
val
config
=
fileNameOption.fold(
ifEmpty
=
ConfigFactory.load() )(
file
=
> ConfigFactory.load(file) )
def
envOrElseConfig(name
:
String)
:
String
=
{
Properties.envOrElse(
name.toUpperCase.replaceAll(
""
"\."
""
,
"_"
),
config.getString(name)
)
}
}
The script can be used as following:
val
myConfig
=
new
MyConfig()
val
value
=
myConfig.envOrElseConfig(
"my.secret.value"
)
println(s
"My secret value is $value"
)
Advantages of Scala
-Scala is ideal for today's scalable, distributed, component-based applications that support concurrency and distribution.
-Scala is statically typed that means that the type of some variable is immutable during the whole execution of the program.
-There is modular mixin-composition for classes - some hack to enable multiple inheritance in Scala, which solves the diamond problem through linearity of the inheritance hierarchy via traits.
-Support of functions that may have other functions as arguments which enables using anonymous functions.
-Lower risk to use Scala in an existing Java Application because Scala works seam less with existing Java Code.
-high level type system with variance annotations, compound types, lower and upper bounds for types usage of inner and anonymous classes implicit conversions - that means a function take one type as an argument and returns to another type (like converting an Integer into String)