Sample type: The class with case added isSample type. This modifier allows the Scala compiler to automatically add some convenient syntax settings for this class.
// Sample class case class // The level includes an abstract base class Expr and four subclasses, each expression represents a kind of expression // The sample class automatically adds the Factory method consistent with the class name abstract class Exprcase class Var (name: String) extends Expr // parameters in the brackets do not need to add val, the default value is the case class Number (num: Double) extends Exprcase class UnOp (operator: String, arg: Expr) extends Exprcase class BinOp (operator: String, left: Expr, right: Expr) extends Expr
Def main (args: Array [String]): Unit = {// 1. The sample class automatically adds the same factory method as the class name, so you don't need new val v = Var ("x"); val op = BinOp ("+", Number (1.0), v ); // 2. All parameters in the sample parameter list implicitly obtain the val prefix, so it is the field var s1: String = v. name
// ================================================ ======================================//// Match corresponds to the Switch // selector match {standby option in Java} replaced switch {selector} {standby option} // A standby option contains a mode and multiple expressions, arrow symbol => separates the pattern from the expression. // This function does not make any changes to the expression. It is only used to return the expression expr def simplifyTop (expr: Expr) used for matching ): expr = expr match {case UnOp ("-", UnOp ("-", e) => e case BinOp ("+", e, Number (0 )) => e case BinOp ("*", e, Number (1) => e
Case _ => expr // if no wildcard is available, an exception is thrown when the matching fails.
} Println (simplifyTop (BinOp ("+", v, Number (0) println (simplifyTop (BinOp ("*", op, Number (1 ))))}
Pattern matching:
Comparison between match and switch: A matching expression can be considered as a generalization of a Java-style Switch. But there are three differences:
- Match is a Scala expression and always uses a value as the result;
- Scala's standby option expression will never "fall" into the next case;
- If there is no mode match, the MatchError exception will be thrown. This means that you must always be sure that everything is taken into account, or add at least one default case to do nothing. For example, case _ =>
Scala Learning document-sample class and pattern matching