Definition of if expression: in Scala, if expression has value, which is the return value of the last statement in if or else expression.
object IfDemo { def main(args: Array[String]): Unit = { val age = 28 val isAdult = if (age > 25) 1 else 0 println(isAdult) } }
Type inference of if expression: because if expression has value, Scala will automatically infer the type of return value, taking the common parent type of value type of if and else expression. For example, if the value type of the expression is Int, else the value type of the expression is Unit, which is also represented by (), then the value type of the expression is Any. Here, Any is the common type of Int and Unit.
While do loop: Scala has a while do loop with the same basic semantics as Java.
object Demo { def main(args: Array[String]): Unit = { var n = 20 // Defining variables while(n > 0) { println(n) n -= 1 } } }
Scala has no for loop, so it can only use while instead of for loop, or use simple for statement
Simple for statement:
object Demo { def main(args: Array[String]): Unit = { val n = 20 // Defining variables for (i <- 1 to n) { println(i) } } }
Scala jumps out of loop statement: Scala does not provide a break statement similar to java, but you can use the break function of boolean variable, return or Breaks instead.
import scala.util.control.Breaks._ object Demo { def main(args: Array[String]): Unit = { breakable { var n = 10 for(c <- "Hello World") { if(n == 5) { break } print(c) n -= 1 } } } }
Scala's 99 multiplication table:
object Demo { def main(args: Array[String]): Unit = { for (i <- 1 to 9; j <- 1 to i) { print(i + "*" + j + "=" + (i * j) + "\t") if (i == j) { println() } } } }
if guard: even
object Demo { def main(args: Array[String]): Unit = { for (i <- 1 to 20 if i % 2 == 0) { println(i + "Even numbers.") } } }
for derivation: constructing sets
object Demo { def main(args: Array[String]): Unit = { val newValue: Seq[Int] = for (i <- 1 to 10) yield { i * 2 } println(newValue) } }
Scala function: when defining a function in Scala, you need to define the function name, parameter, and function body. Scala requires that all parameter types be given, but not necessarily the type of function return value. As long as the function body on the right does not contain recursive statements, Scala can infer the return type according to the expression on the right.
Function definition: def function name (parameter 1: parameter type 1, parameter 2: parameter type 2...) [: return value type] = {function body}
Give an example:
def sum(n: Int) = { var sum = 0for(i <- 1 to n) sum += i sum }
Recursive function and return type: if the function itself is called recursively in the function body, the return type of the function must be given manually.
Example: to realize the classical Fibonacci series
1, 1, 2, 3, 5, 8, 13, ...
def fab(n: Int): Int = { if(n <= 1) 1 else fab(n - 1) + fab(n - 2) }
Default parameter of scala: in Scala, sometimes when we call some functions, we don't want to give the specific value of the parameter, but want to use the default value of the parameter itself, so we can use the default parameter when defining the function.
def sayHello(firstName: String, middleName: String = "Jackson", lastName: String = "Jhon"): String = firstName + " " + middleName + " " + lastName
Variable length parameter of scala: in Scala, sometimes we need to define a function in the form of variable number of parameters, then we can use variable length parameter to define a function.
Give an example:
def sum(nums: Int*): Int = { var res = 0 for (num <- nums) { res += num } res }
Using sequence to call variable length parameter: if you want to call a variable length parameter function directly from an existing sequence, it is not right. For example, val res = sum(1 until 10). In this case, you need to use Scala's special syntax to define parameters as sequences so that the scala interpreter can recognize them.
Example: using recursive function to achieve accumulation
object Demo { def main(args: Array[String]): Unit = { println(sum(1 to 10: _*)) } def sum(nums: Int*): Int = { if (nums.length == 0) { 0 } else { nums.head + sum(nums.tail: _*) } } }
Lazy value in scala: in Scala, the property of lazy value is provided. That is to say, if a variable is declared as lazy, the expression corresponding to the variable will be evaluated only when the variable is used for the first time. This feature is particularly useful for time-consuming computing operations, such as opening files for IO, network IO, etc.
import scala.io.Source._
lazy val lines = fromFile("C://Users//Administrator//Desktop//test.txt").mkString
Even if the file does not exist, it will not report an error. Only when the first variable is used, it will report an error. This proves the lazy feature of expression evaluation.
val lines = fromFile("C://Users//Administrator//Desktop//test.txt").mkString
lazy val lines = fromFile("C://Users//Administrator//Desktop//test.txt").mkString
def lines = fromFile("C://Users//Administrator//Desktop//test.txt").mkString
Exception handling in scala: in Scala, exception handling and capture mechanisms are very similar to Java.
import java.io.IOException object Demo { def main(args: Array[String]): Unit = { try { throw new IllegalArgumentException("x should not be negative") } catch { case _: IllegalArgumentException => println("Illegal Argument!") } finally { println("release resources!") } try { throw new IOException("user defined exception") } catch { case e1: IllegalArgumentException => println("illegal argument") case e2: IOException => println("io exception") } } }