[Introduction to Scala] Scala Basic Grammar: Classes and Objects, Variables and Constants

Please move to [Getting Started with Scala] Scala download and installation (Windows) and Idea to create the first scala project - Programmer Sought

Table of contents

1. Scala

2. Scala Basic Grammar

2.1 Comments and Identifier Specifications

2.2 Variables and constants

[Case: variable declaration and assignment]

2.3 object

[Case: Companion object, val changes attributes through objects]

[Case: Rewrite constructor, apply method in object]


1. Scala

  • Scala is based on the JVM, fully compatible with Java, and also has the characteristics of cross-platform, good execution, and convenient garbage collection ;
  • Scala is a pure object-oriented language;
  • Scala is a functional programming language;
  • Scala has very good support for collection type data processing

The bottom layer of Spark is written in Scla, and you must master Scala to learn Spark in depth.

2. Scala Basic Grammar

Note :

  • There will be a semicolon automatic inference mechanism after each line in scala, no need to explicitly write ";"
  • It is recommended that in scala, the first letter of the class name is capitalized, the first letter of the method is lowercase, and the naming of classes and methods is suggested to conform to the hump naming method

2.1 Comments and Identifier Specifications

(1) Note:

//  	1.单行注释

/* */ 	2. 多行注释

/** 	3. 文档注释
*
**/

(2) Identifier naming convention:

  • Alphabetic underscores followed by alphanumeric underscores, as in C/C++/Java.
  • operator, and only contains (+-*/#!, etc.), is also a valid identifier. Is there any weird benefit to using it this way? The answer is operator overloading that is as flexible as Zentraedi.
  • Any string enclosed in backticks, even if it has the same name as one of the 39 Scala keywords.
var _abc:String = "hello"
val -+/%# = 10
val `if` = 10
println(_abc)
println(-+/%#)
println(`if`)

keywords:

  • package import class obejct trait extends with type for
  • private protected abstract sealed final implicit lazy override
  • try catch finlly throw
  • if else match case do while for return yield
  • def var val
  • this super
  • new
  • true false null
  • Among the keywords that Java does not have:object trait with implicit match yield def val var

String:

  • type:String
  • +connection
  • *String multiplication, copying a string multiple times
  • printfformatted output
  • String interpolation: s"xxx${varname}"prefix stemplate string, prefix fformat template string, by $getting variable value, %followed by format string.
  • Raw string: raw"rawstringcontents${var}", the formatting string that follows will not be considered.
  • Multi-line string: """ """.
  • output:print printf println ...
    val name: String = "Pyrrha" + " " + "Nikos"  // +号拼接字符串
    val age = 17
    println((name + " ") * 3)  // 将一个字符串复制多次进行拼接
    printf("%s : dead in %d\n", name, age) // printf:前缀f格式化模板字符串,通过$获取变量值,%后跟格式化字符串
    print(s"$name : dead in ${age}") // 字符串插值:前缀s模板字符串,通过$获取变量值
    val power = 98.9072
    println(f" : power ${power}%.2f.") // 取小数后2位

2.2 Variables and constants

Scala has two types of variables:

  • The variable declared by the keyword var has a variable value ;
  • The variable declared by the keyword val is also called a constant, and its value is immutable ;

 

Note :

  • If the type of the variable can be inferred from the variable value, then the type declaration can be omitted;
  • Variables must be explicitly initialized;
  • Generally, it defaults to a val type variable;

[ Case: variable declaration and assignment ]

object HelloWorld {
  def main(args: Array[String]): Unit = {
    // 定义方法 main ==  def 方法名(参数名: 参数类型):返回值 ={}
    println("hello world")

    //1. 类型推导; 声明变量时, 类型可以忽略, 编译器会自动推导;
    var a1 = 10;
    var a2: Int = 10;
    var b3 = "areusb?";
    val c5 = false;

    //2. 强类型语言; 变量/常量的数据类型确定后, 就不能再修改
    var e3: Int = 250;
    e3 = "feswgf"; // 编译器不会对此句报错, 执行时才会报错 type mismatch

    //3. 声明变量时必须有初始值,否则报错;
    var e4: Int;

    //4. var可变, va不可变
    var f4 = 6;
    f4 = 9;
    val f5 = 100;
    f5 = 200; // 编译器当场报错;
  }
}

Output results in the console:

2.3 object

The object in scala is a singleton object, which is equivalent to the tool class in java, which can be regarded as a class that defines static methods.

If in the same file, the name of the object object and the class class are the same, then this object is the companion object of this class , and this class is the companion class of this object. Private variables can be accessed from each other.

[ Case: Companion object, val changes attributes through objects ]

  • object cannot pass parameters;
  • The class class in scala can pass parameters by default, and the default parameter passing is the default constructor. When rewriting the constructor, the default constructor must be called;
  • The attributes in the class class have setter and getter methods by default;
package test

class Student(name: String, var age: Int) {
  def printInfo(): Unit = {
    println(name + " " + age + " " + Student.school)
  }
}

// 引入 object 伴生对象/单例对象,所有的私有属性都可以互相访问
object Student {
  val school: String = "atguigu"

  def main(args: Array[String]): Unit = {
    val alice = new Student(name = "alice", age = 19)
    alice.age = 24
    alice.printInfo()
  }
}

Output results in the console: 

[ Case: Rewrite constructor, apply method in object]

  • The class class in scala can pass parameters by default, and the default parameter passing is the default constructor. When rewriting the constructor, the default constructor must be called;
  • When using object, do not use new; when using class, you need new, and when new, except for the method that is not executed in the class (excluding construction), everything else is executed ;

  • The apply method in the object: parameters cannot be passed in the object. When creating an object, if the parameters are passed in, it will automatically find the apply method with the corresponding number of parameters in the object;
package com.yt.test

class Person(xname: String, xage: Int) {
  val name = xname
  var age = xage
  var gender = 'M'
  println("----------- Person Class -----------") // new时,class中除了方法不执行(不包括构造),其他都执行

  def this(yname: String, yage: Int, ygender: Char) {
    this(yname, yage)  // 类中重写构造时,构造中第一行要调用默认的构造函数
    this.gender = ygender
  }

  def sayName() = {
    println("sayName:", ClassAndObj.name) // 调用object静态属性
  }
  println("************ Person Class ************")
}

object ClassAndObj {
  println("----------- ClassAndObj object -----------")
  val name = "wangwu" // object静态属性,相当于java的工具类

  def apply(s: String, age: Int) = {
    println("name is " + s + ",age" + age)
  }

  def main(args: Array[String]): Unit = {
    val p1 = new Person("zhangsan", 19)
    val p2 = new Person("zhangsan", 19, 'F')
    p1.age = 200
    println(p1.name, p1.age)
    p1.sayName()
    println(p2.name, p2.age, p2.gender)

    ClassAndObj("lisi", 500)
  }

}

Output results in the console: 

Guess you like

Origin blog.csdn.net/qq_45956730/article/details/130316536
Recommended