Conditional expression
Unlike java/c + +, if / else syntax in scala has a return value, which is the value of the last expression after if / else.
val s:String = if(1>0) "yes" else "no" // The return value is the common super type of the return value of the if/else expression. Here is String. val value: Any = if (1 > 0) "yes" else 1 // If else does not return a value, the default is Unit type, which is equivalent to void in java, represented by (). val value: Any = if (1 > 0) "yes" else ()
Block expressions and assignments
In scala, block expressions also have a value, which is the value of the last expression in the block. The value of the assignment statement is of type Unit.
val distance: Double = { val a = 2 val b = 4 scala.math.sqrt(a * a + b * b) }
I / O
stay scala.io.StdIn Class contains various methods of input.
val in: StdIn.type = scala.io.StdIn val n: Int = in.readInt() val bool: Boolean = in.readBoolean() val d: Double = in.readDouble() val str: String = in.readLine() //Format input val in: StdIn.type = scala.io.StdIn val list: List[Any] = in.readf("this is {0,number,integer}") // Enter this is one point two two Output 1
If you want to print a value, we use the print or println function, which appends a line break.
There are three kinds of string interpolation in scala.
- f: With formatting command, similar to printf function of other languages.
- s: Without formatting command, commonly used.
- raw: escape sequences are not evaluated.
val name = "yoleen" val age = 10 print(s"My name is $name and I am ${age*2} years old\n") //My name is yoleen and I am 20 years old print(f"My name is $name%s and I am ${age*2.5}%.2f years old\n") //My name is yoleen and I am 25.00 years old print(raw"My name is $name and I am ${age*2.5} years old\n") //My name is yoleen and I am 25.0 years old\n
loop
scala has the same while and do loops as java and c + +. For example:
while(n>0){ r *= n n-=1 //No -- and + + operators }
In scala, the for loop is as follows:
// Syntax structure of for for(elem <- expression){ //Why elem is valued depends on the value in the expression. } for(i <- 1 to 10){ // The to method in the RichInt class returns the Range interval of 1 to n (including n) n += i } for(elem <- "hello"){ //elem = 'h'...'o' } //Followed by Boolean expression for(i <- 1 to 10 if(i%2==0)){ print(f"$i%3d") }//To be handed over //Multiplicative table for(i <- 1 to 9; j <- 1 to i){ print(s"$i*$j=${i*j} ") if(i==j){ println //Omit bracket without reference } } //for derivation, use yield to generate an array of immutable length //Note that there is no {} after for val ints: immutable.IndexedSeq[Int] = for (i <- 1 to 9; j <- 1 to i) yield { i*j }
function
To define a function, you need to give the name, parameters, and body of the function, for example:
def main(args: Array[String])= {}
You have to give the type of all the arguments, but as long as it's not a recursive function, you don't have to specify the return type of the function. scala compiler can infer return type by return value.
For recursive functions, we must specify the return type, for example:
// Recursively multiplies all characters in a string. def recursive(s:String,i:Int):Long={ if(i<s.length){ recursive(s,i+1)*s(i).toInt }else{ 1 } }
Default and named parameters
The initial value can be brought with the function definition. For example:
def sayHello(name:String,s:String="hello,",left:String="[",right:String="]")={ s+left+name+right }//Entering name="yoleen" will output hello,[yoleen]
For functions with more parameters, named parameters can make the program easier to read.
Note that the parameters do not need to be in the same order as the parameter list.
sayHello(s="Hi,",name="yoleen",right="]!") //Hi,[yoleen] will be output!
Variable length parameter
Sometimes you don't know how many parameters to enter. You can use variable length parameters.
//args is a parameter of type seq. def sum(args:Int*)={ var result = 0 for(elem <- args){ result+=elem } result }
Although args is a sequence, this writing is wrong.
val s = sum(1 to 5) //report errors
We can't directly pass the elements in a sequence to a method as variable length parameters. The solution is to treat them as parameter sequences and append them after the sequence:_ *For example:
val s = sum(1 to 5:_*) //Back to 15
lazy
When val is declared lazy, its initialization will be delayed until we value it for the first time. For example:
lazy val file = scala.io.Source.fromFile("File path") //After the variable is defined as lazy, the file will be assigned only when we use this variable for the first time. //lazy is very useful in programs with high initialization cost. //Note: lazy is not without extra cost. Every time we visit the lazy variable, //There is a thread safe way to check if the lazy variable has been initialized.
Coding is not easy. If you think the article is good, please click recommend.