[Scala Basic Grammar] 04. Basic Grammar


insert image description here

1. Keywords

There are some reserved keywords and reserved keyword combinations in Scala which have special meaning and cannot be used as identifiers (variable names, function names, etc.). Following are some keywords in Scala:

1. Keywords

abstract case catch class
def do else extends
false final finally for
forSome if implicit import
lazy match new null
object override package private
protected return sealed super
this throw trait try
true type val was
while with yield

In Scala, keywords are reserved words with special meanings, which play an important role in the code to define the syntactic structure and control the behavior of the code. Following are the roles and functions of some common keywords in Scala:

  1. abstract: Used to declare abstract classes and abstract methods. Abstract classes cannot be instantiated, only inherited and extended. Abstract methods have no actual implementation and must be overridden in subclasses.

  2. case: Used for pattern matching and constructing sample classes. In pattern matching, casekeywords are used to declare pattern matching branches, which can be used to match different values ​​or data structures. At the same time, case classkeywords can be used to define sample classes, which have automatically generated companion objects, comparability and pattern matching characteristics.

  3. class: Used to declare classes. Classes are the basic building blocks in object-oriented programming, encapsulating data and behavior.

  4. def: Used to declare methods. A method is a function defined in a class or object.

  5. if/ else: Used for conditional control statements. ifIt is used for conditional judgment, and different code branches are executed according to the result of the condition. elseUsed to ifexecute another set of code when the condition is not met.

  6. for/ yield: Used for looping and generating collections. forThe keywords are used for loop iterations yieldto generate new collections or results.

  7. trait: Used to declare traits (Trait). Traits are similar to interfaces and can be mixed in multiple classes for code reuse and multiple inheritance.

  8. match: Used for pattern matching. matchKeywords are used to perform pattern matching on an expression, and perform corresponding operations according to the matching results of different patterns.

  9. object: Used to declare objects (singleton objects). An object is a class with a single instance and can be used as a singleton in a program.

  10. extends/ with: Used for class inheritance and trait mixins. extendsSingle inheritance for classes, withfor mixing in multiple traits.

  11. import: Used to import packages or classes. importKeywords are used to bring in members from other classes or packages, making them available in the current code.

  12. var/ val: Used to declare variables and constants. varIt is used to declare mutable variables, whose value can be modified; valit is used to declare immutable constants, which cannot be changed once they are assigned.

In addition to the above keywords, Scala also has some other keywords, such as try, catch, finally, while, do, yield, throwetc., which are used in scenarios such as exception handling, loop control, and exception throwing. These keywords make up Scala's rich syntax, enabling developers to write more flexible and powerful code.

2. Symbol

- : = =>
<- <: <% >:
# @
  1. :: Used in type annotations to specify the type of a variable or expression. For example: val x: Int = 10Indicates that xthe type of the variable is Int.
  2. =: Used to assign or define the value of a variable, function, or method. For example: val x = 42means to define a xvariable named and assign the value 42.
  3. =>: Used to specify the relationship between an anonymous function (Lambda function) or pattern matching and the result. Example: (x: Int) => x * 2Represents an anonymous function that takes a parameter of type Int and returns double of it.
  4. <-: A generator used in a for loop to iterate over the elements in a collection. For example: for (x <- 1 to 5)means to traverse all integers between 1 and 5.
  5. <:: An upper bound constraint for a generic type parameter, indicating that the generic type parameter must be a subclass of a certain type. For example: class MyClass[T <: Number]Indicates that Tit must be Numbera subclass of a class.
  6. <%: Used in type parameter context delimitation, which is now deprecated and no longer recommended.
  7. >: : A lower bound constraint for a generic type parameter, indicating that the generic type parameter must be a parent class of a certain type. For example: class MyClass[T >: Int]Indicates that Tit must be Intthe parent class of the type.
  8. #: Used to access type members, such as type members of a class or type members of a trait. For example: MyClass#InnerClassIndicates access to types MyClassin a class InnerClass.
  9. @: Used for binding (Binding) in pattern matching, which can bind a certain part to a variable when matching. For example: case obj @ MyClass(_, _) => ...means to bind the matched object to a variable obj.

These keywords and keyword combinations have special grammatical meanings in Scala, and you should avoid using them as identifiers when writing code to avoid syntax errors and ambiguities.

2. Notes

In Scala, you can use two types of comments to illustrate and document your code: single-line comments and multi-line comments.

1. Single-line comments

Single-line comments start with double slashes //and are used to comment code or add comment instructions within a line. Single-line comments //extend from the beginning to the end of the line, and the compiler ignores //the content that follows in this line of code.

// 这是一个单行注释
val x = 42 // 这是一个单行注释,用于解释变量的含义

2. Multi-line comments

Multi-line comments use /*and */comment out a piece of code, which can be used for multi-line comments or to comment out a piece of code. Multiline comments can span multiple lines, and the compiler ignores everything between /*and .*/

/*
  这是一个多行注释
  它可以跨越多行
*/

/* 这是一个多行注释,用于注释掉一段代码
val y = 10
val z = 20
*/

Note: Although multi-line comments can span multiple lines, in Scala it is generally recommended to use single-line comments for code comments and explanations, because single-line comments are more concise, clear, and easy to read and maintain.

Comments are an important code documentation tool that help other developers understand the intent and purpose of the code. When writing code, comments should be as clear and precise as possible to help others understand your code better.

3. Naming rules

In Scala, naming refers to choosing appropriate names for identifiers (Identifiers) such as variables, functions, classes, and methods. Good naming can make the code more readable, understandable, and maintainable, and improve the readability and maintainability of the code. Here are some naming conventions and conventions:

  1. Identifier naming rules:

    • Identifiers consist of letters, numbers, and underscores, but must begin with a letter or underscore.
    • Identifiers are case-sensitive, variableand Variableare different identifiers.
    • In addition, Scala also supports the use of operators and ....arbitrary strings enclosed in backticks as identifiers, but it is not recommended, and excessive use will reduce the readability of the code
  2. Variable and constant naming:

    • Variable names usually use a combination of lowercase letters and underscores, for example: age, count, total_amount.
    • Constants usually use a combination of capital letters and underscores, for example: MAX_VALUE, PI.
  3. Function and method naming:

    • Function and method names usually use a combination of lowercase letters and underscores, for example: calculate, process_data.
    • If the function or method returns a Boolean value, it usually starts with isor , for example: , .hasis_validhas_data
  4. Class and object naming:

    • Class names usually start with a capital letter and use camel case, for example: Person, EmployeeData.
    • The naming of objects (singleton objects) also follows the rules of class names, for example: MathUtils, Config.
  5. Package naming:

    • Package names use lowercase letters, and dots ( ) can be used .for hierarchical division, for example: com.example.project.
  6. Generic type parameter naming:

    • Generic type parameters typically use a single uppercase letter, for example: T, E, A.
  7. Concise and meaningful:

    • Naming should be as succinct as possible, but meaningful and able to express its purpose and meaning.
    • Avoid oversimplified single-character naming, which reduces code readability unless in the proper context.
  8. Avoid using reserved keywords:

    • Avoid using reserved keywords in Scala as identifier names, otherwise a syntax error will result.

When naming, it is best to choose a name that can clearly express the meaning, making the code easy to understand and maintain. Try to follow common naming conventions and conventions to be consistent with other Scala developers.

Guess you like

Origin blog.csdn.net/m0_47256162/article/details/132158638