4. Scala function basis
I. built-in control structure
1. If expression
Val filenameNice = if (! args.isEmpty) args (0) else "default.txt"
2. While cycle
Whether it's while or do...while, we can't call it an expression, we should call it a loop, because they don't calculate a new value. Their value type is Unit, and Unit and () are equal in scala
Def gcdLoop (x: Long, y: Long): Long = {
Var a = x
Var b = y
While (a! = 0) {
Val temp = a
A = b% a
B = temp
}
B
}
Do...while... Expression.
Var line = ""
Do {
Line = scala.io.StdIn.readLine ()
Println ("Read:" + line)
} while (line! = "")
Reassigning var in scala always returns () (that is, Unit)
()! = "will return true forever
Var tempLine = ""
While ((tempLine = scala.io.StdIn.readLine ())! = ") / / This doesn't work!
Println ("Read:" + tempLine)
Because the while loop does not calculate the value, the while code is not so functional and generally contains the var variable
Scala chose to keep while because the code that uses while in some scenarios is still very readable.
Using recursion to eliminate var
Def gcd (x: Long, y: Long): Long =
If (y = = 0) x else gcd (y, x% y)
3. For expression
Iterate over an arbitrary set with for expression
Val filesHere = (new java.io.File ("."). ListFiles
For (file