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

  • Professional Scala
  • Mads Hartmann Ruslan Shevchenko
  • 314字
  • 2021-07-23 17:24:23

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
     }
}
主站蜘蛛池模板: 德庆县| 东安县| 泾源县| 碌曲县| 桃江县| 新密市| 兴城市| 石泉县| 万盛区| 淮阳县| 廊坊市| 尖扎县| 石台县| 南投县| 商水县| 石棉县| 台东市| 香河县| 玉溪市| 安图县| 秭归县| 平邑县| 桑日县| 和龙市| 简阳市| 汝阳县| 永州市| 嘉禾县| 嫩江县| 锡林郭勒盟| 罗源县| 扬中市| 永吉县| 青州市| 正安县| 龙山县| 象山县| 壶关县| 洪湖市| 吉木萨尔县| 汉阴县|