Two, Scala control structure and functions

1. Conditional expression

Scala the if/elseexpression: val s = if (x>0) 1 else -1This expression is equivalent to: if(x>0) s = 1 else s = -1
in Scala, each expression has a type.
if (x>0) 1 else -1type is Int
the type of expression ② mixing two types of public branches supertypes, for example: if (x>0) "positive" else 1its type Intand java.lang.Stringcommon supertype Any
③ If the else part is missing, it will be Unitclass instead, for example: if (x>0) 1equivalent to if (x>o) 1 else (), Can be ()understood as a placeholder for "no useful value".

2. Statement termination

①Use ;separation when writing multiple statements on the same line.
②When writing a longer statement, divide it into two lines. Make sure that the first line ends with a symbol that cannot be used as the end of the statement. For example, in a summation statement, The line +ends.

3. Block expression and assignment

① When you need to place multiple actions in a logic branch or soul ring, you can use a block statement {语句序列}. The value of the last expression in the block is the value of the block. This feature requires multiple steps to initialize a val. The situation is very useful.

val distance = {
    
    val dx = x-x0; val dy = y - y0; sqrt(dx * dx + dy * dy)}

The value of this block is the result of the last square root

②In Scala, the assignment action itself has no value. Its value is of Unittype, and the value of a block that ends with an assignment statement is of Unittype. Example: { r = r*n; n-=1}The value type is Unit.
Therefore, you cannot string assignment statements together. For example x = y = 1, assigning y = 1the value of Unitx to x seems meaningless.

4. Input and output

① Output
String interpolation:
print (f"Hello, $name! In six months, you'll be ${age + 0.5}%7.2f years old.%n")
Among them: the formatted string fstarts with a letter , and $the expression starting with the beginning can be replaced with the corresponding variable. Using an finterpolator is better than using a printfmethod because it is type safe. There are three types of string interpolators, which will not be expanded in detail.
②Input
You can use scala.io.StdInthe readLinemethod to read a line of input from the console. If you want to read numbers, Booleans or characters, use them readInt,readDouble,readBytes,readShort,readLong,readFloat,readBoolean,readChar. Among them, the readLinedifference is that it takes a parameter as a prompt stringStdIn.readLine("your name:")

5. Loop

①The whileusage method is not different from other languages
②The fordifference is big:for (i <- 表达式)

for(i<- 1 to 10)
	r=r*i

var sum = 0
for(ch<-"hello")
	sum+=ch

③Scala does not provide break and continue statements to exit the loop, you can use the following methods:

  • Use Boolean control variables
  • Use nested functions-you can return in the function
  • Use the break method in the Breaks object
import scala.util.control.Breaks._
breakable{
    
    
	for(`````){
    
    
		if(````)break;//退出breakable块
		····
	}
}
但不建议使用这种机制,比较慢

6. Advanced for loop

May be 变量<-表达式provided in the form of a plurality of generators, they are separated by semicolons

for(i<-1 to 3; j<-1 to 3)
	·····
相当于双重循环,i为外循环,j为内循环

Every generator can bring a guard (note that there is no semicolon before the if)

for(i<-1 to 3; j<-1 to 3 if i!=j)
过滤掉i==j的情况

You can also use the definition

for(i<-1 to 3;from 4-i; j<-from to 3)

Note:
If the body of the for loop yieldstarts with, the loop will construct a set, and each iteration generates a value in the set:

for(i<-1 to 10) yield i%3
将交出一个vector(120120·····)

You can use newline characters instead of semicolons

7. Function

def abs(x:Double) = if(x>=0) x else -x

As shown in the above example: you need to give the name of the function, the parameters and the body of the function, and the types of all the parameters must be given.
As long as the function is not recursive, it is not necessary to specify the return value type. The Scala compiler can infer the return value type from the expression on the right side of =. But for recursive functions, you must indicate the return value type:

def fac(n:Int) :Int = if(n<=0) 1 else n*fac(n-1)

8. Default parameters and named parameters

The default value is not much different from other languages.
You can specify the parameter name when you provide the parameter.

decorate(left = "<<<",str = "Hello",right = ">>>")

Because the parameter name is specified, the order of the parameters can be inconsistent with the parameter list

9. Variable length parameters

Implement a function that can accept variable length parameter lists

def sum(args :Int*){
    
    
	var result = 0
	for (arg<-args) result +=arg
	result
}

The parameters of the function are any number

val s = sum(1,4,5,6,6,6,6)

The function gets a parameter of type Seq

If you already have a value sequence, you cannot pass the value sequence directly into the function. If the parameter passed in when the sum function is called is a single parameter, the parameter must be a single integer, not an integer range:, the val s = sum( 1 to 5) //是错误的correct way to write is val s = sum(1 to 5:_*), which is _*used to convert it into a sequence of parameters.

**Note:** When you call a Java method with variable length parameters and the parameter type is Object, for example Print Stream,Printf,MessageFormat.format, you need to manually convert the basic type.

val str = MessageFormat.format("The answer to {0} is {1}",
"everything",42.asInstanceOf[AnyRef])

10. Process

There is a special way of expression for functions that have no return value. If the function body is wrapped in {}, but there is no = in front, it means that the return value type is Unit, and the function is called a process.

def box(s :String){
    
    
····
}

11. Lazy value

When valis declared lazy, it is initialized will be delayed until the first time we value it.

lazy介于val和def之间,val是被定义时就取值,而def是每次调用时取值
lazy val words = scala.io.Source.fromFile("").mkString

12. Abnormal

Scala has no "checked" exceptions, and we don't need to declare that functions or methods may throw some kind of exception. I don't know much, so I won't write it in detail.

Guess you like

Origin blog.csdn.net/Cxf2018/article/details/109406540