Search icon CANCEL
Subscription
0
Cart icon
Your Cart (0 item)
Close icon
You have no products in your basket yet
Arrow left icon
Explore Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Free Learning
Arrow right icon
Arrow up icon
GO TO TOP
Professional Scala

You're reading from   Professional Scala Combine object-oriented and functional programming to build high-performance applications

Arrow left icon
Product type Paperback
Published in Jul 2018
Publisher
ISBN-13 9781789533835
Length 186 pages
Edition 1st Edition
Languages
Tools
Arrow right icon
Authors (2):
Arrow left icon
Ruslan Shevchenko Ruslan Shevchenko
Author Profile Icon Ruslan Shevchenko
Ruslan Shevchenko
Mads Hartmann Mads Hartmann
Author Profile Icon Mads Hartmann
Mads Hartmann
Arrow right icon
View More author details
Toc

Base Syntax

Now that we can use REPL, let's understand the base Scala syntax. For now, it's not necessary to learn it in detail, but let's get familiar with it by using an example.

Note

For a formal, detailed description, refer to the SLS: Scala Language Specification here: http://scala-lang.org/files/archive/spec/2.12/.

Base Syntax for Definitions

Scala compilation unit – This is a set of definitions inside an entity (template-entity), which can be an object, a class, or a trait. We will speak about the Object-Oriented part of the Scala language in detail later. Now, let's look at the basic syntax. Let's define some classes in REPL:

> class X {  def f():Int = 1 }
> Class X defined  // answer in REPL

Definitions inside the entity can be nested entities, functions, or values:

> def f():Int = 1

Here, the function f is defined, returning 1. We will talk about this function in detail in Chapter 3, Functions. Now, let's stay on the top-level view:

> val x = 1

Here, the value x is defined with value 1:

> var y = 2

Here, the mutable variable y is defined with value 2.

Other high-level entities include objects and traits. We can create objects by writing object or trait definitions:

>  object O {  def f():Int =1  }
>  trait O {  def f():Int =1  }


We will talk about classes, objects, and traits in the next chapter.

Now, let's look at defining an object in REPL with the name ZeroPoint.

Steps for Completion:

  1. Open REPL by typing the following command in sbt:
    sbt console
  2. Type in the following commands in REPL:
    >  object ZeroPoint {
    >     val x:Int = 0
    >     val y:Int = 0
    > }

Base Syntax for Expressions

Scala is an expression-based language, which means that everything is an expression (in the right-hand side of function and value/variable definitions).

Some of the base expressions are:

  • Primitive expression: Constant or value/variable name.
  • Function calls: These can be:
    • Usual function calls f(x, y).
    • Operator call syntax:
    • binary: x + y.

    Note

    Any method with an argument can be used as a binary operator. A set of predefined binary operators are similar to Java:

  • unary: !x
  • Constructors: new x creates an instance of class x.
  • Assignments to mutable variables:
    • y = 3: Assigns a value of 3 to y.
    • x = 3: This is a compiler error, and a value can't be assigned.
  • Block:
    { A; B }

    The value of a block expression is the last expression. Note that ; can be omitted if A and B are situated on different lines. The syntax for this is shown as follows:

    {
       A
       B
    }

The preceding syntax will have the same output as { A; B }.

  • Control structures
    • if statement:
             >  if (1 == 1)  "A"  else "B"
             - let's eval one in REPL
    • match/case expressions:
          >  x match {
               case "Jon"  =>  doSomethingSpecialForJon()
               case "Joe" =>   doSomethingSpecialForJoe()
               case   _   => doForAll()
            }
    • Loops:
    • while/do
           var i=0
            var s=0
            while(i < 10) {
                s = s+i
                i = i +1
            }
    • Do/while
    • Foreach, for

Shortcuts for height-order functions will be described in detail in, Chapter 4, Scala Collections.

We'll look at defining a main function which prints something onscreen and calls the main function.

  1. You should have already opened project1. If you haven't, import it into the IDE.
  2. Insert the new method inside the object definition.
  3. Insert call at the main method.

The full method should look something like this:

  object Chatbot1 {def printHello():Unit = {
println("Hello")}def main(args: Array[String]): Unit = {
printHello() … // unchanged code here
     }
}
You have been reading a chapter from
Professional Scala
Published in: Jul 2018
Publisher:
ISBN-13: 9781789533835
Register for a free Packt account to unlock a world of extra content!
A free Packt account unlocks extra newsletters, articles, discounted offers, and much more. Start advancing your knowledge today.
Unlock this book and the full library FREE for 7 days
Get unlimited access to 7000+ expert-authored eBooks and videos courses covering every tech area you can think of
Renews at $19.99/month. Cancel anytime
Banner background image