官术网_书友最值得收藏!

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
    > }
主站蜘蛛池模板: 饶平县| 宜丰县| 宁河县| 漳浦县| 安阳县| 宜君县| 河源市| 敦化市| 陈巴尔虎旗| 运城市| 文化| 若尔盖县| 通江县| 樟树市| 昌吉市| 泰安市| 大英县| 克什克腾旗| 米易县| 永清县| 蚌埠市| 枣阳市| 吴堡县| 禹州市| 建湖县| 景德镇市| 阜平县| 南靖县| 广灵县| 洪江市| 龙胜| 新宾| 绍兴县| 佛学| 祁连县| 卢氏县| 册亨县| 连城县| 美姑县| 墨脱县| 通渭县|