Scala -- basic syntax

Keywords: Scala Spark

1. Brief description of syntax

/*
	object: Keyword to declare a singleton object (companion object)
*/
object HelloWorld{
	/*
	main Method: the executed method can be called directly from the outside
	def Method name (parameter name: parameter type): return value type = {method body}
	*/
	def main(args: Array[String]):Unit = {
		println('Hello World')
		System.out.println('hello scala java')}
	
}

2 basic grammar

2.1 notes

(1) Single line note://
(2) Multiline comment: / * */
(3) Document notes:
/**
*
*/

2.2 variables and constants

  1. Basic grammar
    Var variable name [: variable type] = initial value var i:Int = 10
    val constant name [: constant type] = initial value val j:Int = 20
    Note: variables are not used where constants can be used
  2. be careful
    (1) When declaring a variable, the type can be omitted and the compiler deduces automatically, that is, type derivation
    (2) After the type is determined, it cannot be modified, indicating that Scala is a strong data type language
    (3) Variable declaration must have an initial value
    (4) When declaring / defining a variable, you can use var or val to modify it. The variable modified by var can be changed, and the variable modified by val cannot be changed

var modified objects and object references can be changed, while val modified objects are immutable, but object references can be changed

object TestVar{
	def main(args: Array[String]):Unit = {
		//p1 is modified by var, the attribute of p1 is variable, and p1 is also variable
		var p1 = new Person()
		p1.name = 'dalang'
		p1 = null

		//p2 is modified by val. p2 itself is immutable (the memory address cannot be changed), but the attribute of p2 is variable
		val p2 = new Person()
		p2.name = 'jinlian'
		//p2 = null. This is wrong
	}

	class Person{
		var name : String = 'jinlian'
	}
}

2.3 naming conventions for identifiers

(1) Begin with a letter or underscore followed by letters, numbers, and underscores
(2) Starts with an operator and contains only operators (+ - * / #! Etc.)
(3) Any string included in backquotes ` ` can be even Scala keywords (39)

//These are OK
var hello: String = ''
var hello12: String = '123'
var +-*/ : String = ''
var `if`: String = ''

2.4 string output

(1) String, connected by + sign
(2) printf usage: string, passing value through%.
(3) String template (interpolation string): get variable value through $

object TestPrint{
	def main(args: Array[String]): Unit = {
		val name : String = "alice"
		val age : Int = 18
		// +Splicing
		println(age + "Year old" + name + "At school")
		println(name * 3)

		//printf
		printf("%d Year old%s At school", age, name)

		//String template
		println(s"${age}Year old ${name}At school")

		val num : Double = 2.3451
		println(f"The num is ${num}%2.2f") //The num is 2.35
		println(raw"The num is ${num}%2.2f")  //The num is 2.3451%2.2f outputs whatever it is

		//Three quotation marks represent a multiline string
		val sql = s"""
			|select *
			|from
			|  student
			|where 
			|  name = ${name}
			|and
			|  age > ${age}
			|""".stripMargin
		println(sql)
		}
	}

2.5 keyboard input

Basic syntax: StdIn.readLine(), StdIn.readShort(), StdIn.readDouble()

import scala.io.Source
import java.io.{File, PrintWriter}
object TestStdIn{
	def main(args : Array[String]): Unit = {
		println("Please enter your name")
		val name : String = StdIn.readLine()
		println("Please enter your age")
		val age : Int = StdIn.readInt()

		//output
		println(s"welcome ${age}Year old ${name}The arrival of")
		//Read data from file
		Source.fromFile("./data").foreach(println)
		//scala does not write files, so it needs to borrow java
		val writer = new PrintWriter(new file(path = "./"))
		writer.write("hello scala from java writer")
		writer.close()		
	}
}

2.6 data type


Data type:
(1) All data in Scala are objects and subclasses of Any.
(2) In Scala, data types are divided into two categories: numeric type (AnyVal) and reference type (AnyRef). Both value type and reference type are objects.
(3) Scala data types still adhere to the principle of automatic conversion (implicit conversion) from low-precision value types to high-precision value types
(4) StringOps in Scala is an enhancement to String in Java
(5) Unit: corresponds to void in Java. It is used for the position of the return value of the method, indicating that the method has no return value. Unit is a data type, and only one object is (). Void is not a data type, but a keyword
(6) Null is a type, and only one object is null. It is a subclass of all reference types (AnyRef).
(7) Nothing is a subclass of all data types. It is mainly used when a function has no explicit return value, because in this way, we can return the thrown return value to any variable or function.

2.7 integer type (Byte, Short, Int, Long)


(1) Scala integer types have fixed representation range and field length, which are not affected by specific operations, so as to ensure the portability of scala programs.

var n1 : Byte = 127
var n2 : Byte = -128
var n3 : Byte = 128   //Error prone code slice

(2) Scala integer, which is Int by default, declares Long, and must be followed by 'l' or 'l'

var n4 = 12 //It defaults to Int
var n5 = 1234667899999954L //If Int is exceeded, it needs to be declared as Long type, followed by 'l' or 'l'

(3) Variables in Scala programs are often declared as Int, and Long is used unless it is insufficient to represent a large number

2.8 floating point type (Float, Double)

  1. classification
var n6 = 2.3423f  //The default is Double type. You need to add "F" or "F" to specify it as Float type
var n7 = 3.567    //Double type

2.9 character type (Char)

The character type can represent a single character, and the character type is Char.
(1) A character constant is a single character enclosed in single quotation marks'.
(2) \ t: a tab stop to align.
(3) \ n: newline character
(4) \: indicates
(5) : indicates

val c1 : Char = 'a'

2.10 boolean type: Boolean

(1) Boolean type is also called boolean type. Boolean type data can only take values of true and false
(2) boolean type takes up 1 byte.

var isResult : Boolean = false
var isResult2 : Boolean = true

2.11 Unit type, Null type and Nothing type


(1) The Unit type is used to identify a process, that is, a function without an explicit return value. The Unit has only one instance - (). The method returns a null value.
(2) Null class has only one instance object. Null can be assigned to any reference type (AnyRef), but cannot be assigned to value type (AnyVal). Null reference
(3) Nothing can be used as the return type of a method without a normal return value. It intuitively tells you that this method will not return normally. Moreover, because nothing is a subclass of any other type, it can also be compatible with methods that require a return value.

object TestNull{
	//1. Null value Unit
	def m1(): Unit = {
		println('m1 Called execution')
	}
	val a : Unit = m1()
	println("a: " + a)
	//Return: m1 is called to execute a: ()

	//2. Null reference
	var Student: Student = new Student(name = "alice", age = 20)
	student = null   //Student is a reference type, so it can be assigned null
	println(student)

	//3. Nothing: subclasses of all types
	def m2(n : Int): Int = {	//To specify as the parent class of Nothing and Int types, you can select Int and Any
		if (n == 0)					//In order not to be so broad, you can choose Int
			throw new NullPointException
		else
			return n

	}
	val b : Int = m2(2)
	println("b: " + b)
	//Return b: 2
}

2.12 type conversion

2.12.1 automatic value type conversion

When the Scala program performs assignment or operation, the type with low precision is automatically converted to the numerical type with high precision, which is automatic type conversion (implicit conversion). The data types are sorted according to the precision (capacity):
Basic description:
(1) Automatic promotion principle: when there are multiple types of data mixed operation, the system will first automatically convert all data into the data type with high precision, and then calculate.
(2) When assigning a value type with high precision to a value type with low precision, an error will be reported. On the contrary, automatic type conversion will be carried out.
(3) (byte, short) and char are not automatically converted to each other.
(4) Byte, short and char can be calculated. When calculating, they are first converted to int type.

2.12.2 cast type

The inverse process of automatic type conversion converts a numeric type with high precision to a numeric type with low precision. When using, a forced conversion function should be added, but it may cause precision reduction or overflow. Pay special attention.
(1) To convert data from high precision to low precision, you need to use forced conversion.
(2) The strong conversion symbol is only valid for the most recent operand, and parentheses are often used to promote priority.

var r1 : Int = 2.5.toInt  //Direct rounding (no matter positive or negative, no matter rounding up or down, it will not be rounded)
var r2 : Int = (10 * 3.5 + 6 * 1.5).toInt

2.12.3 conversion between numeric type and String type

(1) Basic type to String type (Syntax: the value of basic type + "").
(2) String type to basic numeric type (Syntax: s1.toInt, s1.toFloat, s1.toDouble, s1.toByte, s1.toLong, s1.toShort).

//Basic type conversion String
var str1 : String = 100 + ""
var str2 : String = 4.5 + ""
var str3 : String = true + ""

//String type to basic numeric type (call related methods)
var s1 : String = "12"
var s2 : Short = s1.toShort
var s3 : Int = s1.toInt
var s4 : Long = s1.toLong

Posted by quimkaos on Sun, 24 Oct 2021 11:44:53 -0700