This article will cover the fundamentals of Scala language.

Values

In Scala, we work with values:

Values are used to define constants. val modifier means constant or immutable that means we cannot change its value once it is created. Thus reassignment to val is prohibited.

It is evaluated at time of definition only. Once evaluated, it reuses same value for all references of it.

Variables

Scala also allows us to define mutable values. Variables are used to define mutable reference to a value. var modifier means changeable or mutable that means we can change its value throughout the program lifetime . Thus reassignment to var is allowed.

We do have the notion of a variable in Scala, but it’s heavily discouraged. In general, we work with immutable data structures: any intended modification to an existing instance should return a new (modified) instance.

Types

In Scala, we don’t always need to specify the data type of our value, because the compiler is smart enough to infer that for us. We can also write:

We can see, the compiler automatically inferred the data type of the value.

Strings

Strings in Scala are similar to what we see in other languages, but with some special functionalities:

String is defined as:

Whenever compiler encounters a string literal in the code, it creates a String object of java.lang.String class with its value.

Methods used to obtain information about an object are known as accessor methods.

One accessor method that can be used with strings is the length() method, which returns the number of characters contained in the string object.

The String class includes a method concat() for concatenating two strings. But strings are more commonly concatenated with the + operator.

String interpolation can also be done using string interpolator. It allows the direct usage of variable in processing a string, by injecting a value with the $ sign.

#scala #tech blogs #basics #scala #strings #types

Scala Beginner Series (1) : Basics
1.35 GEEK