Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

scala

What are the basics of Scala?

Sheza Munir

In this shot, we’ll cover the basics of Scala. The following topics will be covered:

  • expressions (values and variables)
  • blocks
  • functions
  • classes
  • main method

Expressions

Expressions are computable statements. The result of an expression can be output by using the println function.

Example:

println(1+3)
// outputs '4'

The results of evaluated expressions can be stored in values using the val keyword. Values cannot be reassigned.

Example:

val x: Int = 1 + 3

Variables are values that can be re-assigned. The results of evaluated expressions can be stored in variables using the var keyword.

var x: Int = 1 + 3
x = 2 // re-assignment is allowed with variables

Blocks

We can combine expressions by enclosing them in curly brackets: {}. The enclosed part is called a block. The result of the last expression is the result of the overall block.

println({
  var x = 1 + 3
  x = 2
}) // outputs '2'

Functions

Functions are blocks of code that can take arguments. Functions can be named or unnamed.

Named:

val addOne = (x: Int) => x + 1
println(addOne(1)) // outputs '2'

Unnamed:

(x: Int) => x + 1

The list of parameters being used is to the left of =>, while the expression using those parameters that the function computes is to the right.

Classes

Classes are blueprints for objects. They can contain functions, variables, values, etc. An object is an instance of a class.

We define classes with the class keyword, followed by name and constructor parameters. A minimal class definition is simply the keyword class and an identifier. Class names should be capitalized.

Example:

class User

val user1 = new User
}

Main method

The main method of function is the starting point of a Scala program. We declare this using the keyword main.

object HelloWorld {
  def main(args: Array[String]): Unit = {
    println("Hello, world!")
  }
}

RELATED TAGS

scala

CONTRIBUTOR

Sheza Munir
Copyright ©2022 Educative, Inc. All rights reserved
RELATED COURSES

View all Courses

Keep Exploring