In Scala, you can assign the value of a if/else expression to a variable such as: Val s = if (x > 0) 1 Else o
var sum = 0;val s = = "Hello" for (i <-0 to S.until s.length)//until method returns an interval sum of + = s (i) that does not contain the upper bound
Or you don't need to use subscript
var sum = 0for (ch <-"Hello") sum + = ch
Each generator can take a guard with a Boolean expression that begins with the IF
<pre name= "code" class= "Java" >for (I <-1 to 3, J <-1 to 3 if I-j) println ((i*10 + j) + "")//will print 12 13 21 23 31 32//Note If there is no semicolon in front
If the loop body cycle starts with yield, the loop constructs a new collection, each iteration generating a value from the collection
for (I <-1 to ten) yield I% 3//vector (1,2,0,1,2,0,1,2,0,1)
The fort derivation and its first generator are type-compatible
for (c <-' Hello "; I <-0 to 1) yield (c + i). tochar//will generate" Hieflmlmop "for (I <-0 to 1; C <-" Hello ") yield (c+i) The. tochar//will generate vectors (' H ', ' e ', ' l ', ' l ', ' o ', ' I ', ' f ', ' m ', ' m ', ' P ')
In Scala, in addition to supporting methods, functions are supported, methods manipulate objects, and functions are not.
To define a function, you need to give the name of the function, the arguments, the function body, for example:
def abs (x:double) = if (x > 0) x else-x//as long as the function is not recursive, you do not need to specify the return type, and the Scala compiler can infer the return type by the type of the right-hand expression of the = symbol
If a function requires more than one expression to complete, you can use a block of code, and the value of the last expression in the block is the return value of the function.
def FAC (x:int) = {var R = 1for (i <-i to n) R = R * IR}
For recursive functions We must specify the return type. For example:
def FAC (x:int): Int = if (n <= 0) 1 Else n * FAC (N-1)//If there is no return type, the Scala compiler cannot verify the type of n * FAC (N-1)
Implement a function that can accept a variable-length argument list
val s = SUM (1,2,3,4,5)
function will get a parameter of type seq
Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.
Scala Learning Chapter II