How to use Scala for Loop
This article introduces the knowledge of "how to use the Scala for cycle". In the operation of actual cases, many people will encounter such a dilemma, so let the editor lead you to learn how to deal with these situations. I hope you can read it carefully and be able to achieve something!
Basic syntax: variable, definition of variable: immutable: val a = 2 or val a: Int = 2 (data type specified) lazy val a: Int = 2
Variable: var a = 2 or var a: Int = 2 (data type specified)
Def a = 2
The definition variable cannot be 1. Start with a number and a special symbol (except _). Start with keywords (var, val, class, etc.)
What def defines is?
After var compilation, there are set and get square ☐ methods, so you can re-assign values.
After val is compiled, there are only get methods, so you can no longer assign values.
Lazy lazy variable, which is instantiated only when the variable is called, and can only be followed by val
Def and val are almost unable to reassign values. More decorations.
Type of Scala variable: Any is the top-level type of scala. There are two subclasses of AnyVal (value type) and AnyRef (reference type) under Any.
AnyVal: it has nine types, seven of which refer to types: Double Float Byte Int Short Long Char and two non-value types: Unit Boolean
AnyRef: is a reference type whose subclasses are: List Option or class that is custom and inherits it
All types require uppercase initials
Scala automatically infers types
Scala data types can be converted from low to high Byte-Short-Int-Long-Float-Double
Char-Int-Long-Float-Double
Note: there is no strong turn in scala.
Operator
There is no concept of operators in Scala. So-called operators are actually methods.
Mathematical operation: +-* /:%. + () Note: xroomy is equivalent to x.+ (y).
Relationship:
< >=!
Bit operation: | & ^
If two variables of different types operate, the type of the final result is the larger one.
If you want to format the output: var x = 5 var y = 5
Var n = x + y
Print (s "x+y=$n") output result x+y=10
Of course, you can also add the string "xSecrety" to the result.
Conditional expression
This typing is empty because there is not a value in else, but an assignment statement.
Normally, it should be var res = if (sex = = 1) {"male"} else {"female"}
Because there is only one 'expression' in curly braces, curly braces can be omitted
Var res = if (sex = = 1) "male" else "female"
For cycle
For (I)