Spark basic study notes: Scala operators

1. Operators are equivalent to methods

In Scala, operators are methods and methods are operators. Operators in Scala are actually another manifestation of ordinary method calls. The use of operators is actually to implicitly call the corresponding method.

(1) The operator is the method

insert image description here

(2) The method is the operator

1. Single parameter method

val str = "abcdef"
val x1 = str.indexOf('c')
val x2 = str indexOf 'c'

insert image description here

2. Multi-parameter method

val x3 = str.substring(2, 4)
val x4 = str substring (2,4) // 如果参数有多个,需要用小括号包起来 

insert image description here

3. No parameter method

val x5 = str.toUpperCase()
val x6 = str.toUpperCase // 方法调用时如果不需要传入任何参数,小括号可以省略
val x7 = str toUpperCase // 这种写法,如果没有参数,则括号不用写

insert image description here

Two, Scala operator

(1) Operator Classification Table

insert image description here

(2) Comparison of Scala and Java operators

In Scala, if it is a basic data type, == and != compare values; if it is a complex data type, it will implicitly call equals for comparison, which means that there is no classic equals problem in Java in Scala.

insert image description here

3. Types of operators

(1) Infix Operator (Infix Operator)

operator 2 + 3 between the two operands is equivalent to (2).+(3)
insert image description here

(2) Prefix Operator (Prefix Operator)

operator before the only operand: -1, +3, ~0xFF, !false
insert image description here

The only operators that can be used as prefix operators are +, -, !, and ~. If you define the unary_! method yourself, you can use the ! prefix operator to call the method, but even if you define unary_*, it cannot be used to call the method, because it is not one of the four available prefix operators.
insert image description here

(3) Postfix Operator (Postfix Operator)

The operator str toUpperCase is equivalent to str.toUpperCase() after the only operand, and the postfix operator invokes a no-argument method without dots or parentheses. In Scala, the empty parentheses of method calls can be omitted, but if removing the parentheses may cause side effects, bring the parentheses.
insert image description here

4. Operator precedence

(1) Brief description

Since Scala does not have real operators, operators are actually a form of methods, so the priority of operators here actually refers to the priority of methods. The execution of methods in Scala is different in priority, which is also to solve the problem of traditional operator priority.

insert image description here

(2) Operation priority table

Operators with the highest precedence are at the top of the table, and those with lower precedence are at the bottom. In an expression, operators with higher precedence will be evaluated first

insert image description here

Guess you like

Origin blog.csdn.net/py20010218/article/details/125344439