Scala (b) - basic grammar (distinguished from Java's) and functional programming

Scala QuickStart (b)

A keyboard input

About the basic types of operations, as well as knowledge copy operation, conditional operators, and other operators, and all Java language, but more narrative here.

val name = StdIn.readLine()

StdIn is a companion object, can be used directly point calls.

For example:

object VarDemo {
  def main(args: Array[String]): Unit = {
    Test.test()
  }
}
object Test{
  def test(): Unit ={
    println("test")
  }
}

In this case, we know the method object associated object, the equivalent static method can be called directly, in the first section, we can still know that after this decompiler is a static method.

We in the source code, you can see, this StdIn integrates a StdIn actually use the modified trait, trait equivalent in Java Interface. See the following example.

object main {
  def main(args: Array[String]): Unit = {
    VarDemo.inter()
    VarDemo.another()
  }
}
object VarDemo extends  Test {
  def another(): Unit ={
    println("another")
  }
}
trait Test{
  def inter(): Unit ={
    println("inter")
  }
}

In this case, we know the method trait modified class on a similar interface associated class inherits this interface, the middle of the method can also be called directly with point

Other read from the keyboard method

    val a=StdIn.readLine()
    val b=StdIn.readInt()
    val c=StdIn.readDouble()

Second, the branch of the process

exactly the same if statement and Java

Loop control

1.for(变量<-start to end)

for(i<-1 to 3){
  println(i)
}
 i 从1到3,双闭区间

2.for cycle traverse the set (for each cycle similar in Java)

var list =List("1",2,3.0)
for(item<-list)
    println(item)

3.for(变量<-start until end)

for(i<-1 until 3){
  println(i)
}
i从1到3,左闭右开

4.for loop guard, for loop can add additional conditions

for(i<-1 to 3 if i != 2)
    println(i)

Note: continue and there is no break in scala

5.for loop variable is introduced, may be separated by semicolons, embedded in the for loop statement

for(i<-1 to 3 ; j=5-i)
    println(j)

6.for return cycle value, stored in a Vector 1-10 and return

val res=for(i<-1 to 10) yield i
    println(res)
val res=for(i<-1 to 10) yield {
  if(i % 2 == 0){
    i
  }else{
    "不是偶数"
  }
}
println(res)

7. Range (start, end, step) to traverse

for(i<-Range(1,10,3)){
    println(i)
}

While loop and do ... while loop (not recommended)

Java syntax and the same

科普:scala不存在break,如果我想break掉,应该怎么做?

Scala在语言设计上没有break,但是,在Break类中有一个Break.break()来进行异常退出,作者认为,break和continue不属于面向对象和函数式编程,所以在设计语法的时候,没有把这两个字加上去
举例:
    var i=1
    breakable(
      while(true){
        println(i)
        i+=1
        if(i==3) {
          break()
        }
      }
    )
    println("break了")

Third, the functional programming

What is functional programming, similar to a variable passed to a function itself. The following is a small example of functional programming.

var fun=(a:Int,b:Int)=>a+b
println(fun(1,2))

1. Definition Function

def function name (parameter name: parameter type, parameter names: Parameter Type) {

return return value

}

object o{
  def main(args: Array[String]): Unit = {
    println(cacu(1,2,'-'))
  }

  def cacu(a:Int,b:Int,op:Char):Int={
    if(op=='+')  return a+b;//是否写return都ok
    else if(op=='-')  a-b;
    else  0
  }
}

If we are not sure what type of return is that you can put: Int removed, this can be written as:

def cacu(a:Int,b:Int,op:Char)={
    if(op=='+')  a+b;//是否写return都ok
    else if(op=='-')  a-b;
    else  "op输入错误"
}

Note: In this case, you can not use return

2. recursive function

Recursive functions, not performed before the results can not be inferred type, it is necessary to clear the return value type

3. Variable parameters

* Denotes a variable parameter, after the type of load

Case:

def main(args: Array[String]): Unit = {
    println(sum(10,20,30,40))
  }
  def sum(n:Int,args:Int*):Int ={
    var s=n
    for(item<-args){
      s+=item
    }
    return s
  }

Check the following code is correct

def f1="steve yu"
println(f1)

Correct definition of a function f1, return steve yu

4. The process of writing function

def f():Unit={
    函数体
}

This can be abbreviated as

def f(){
    函数体
}

5. Inert function (lazy loading)

Function to load when in use

object Test {
  def main(args: Array[String]): Unit = {
    lazy val a=pr();//调用的时候不加载
    println("-"*20);
    println("."*20);
    a.hashCode()//使用的时候加载
  }
  def pr(): Unit ={
    println("lazy function")
  }
}
该函数的执行结果:
--------------------
....................
lazy function

We should note that, in the course of the inert function, only modified val, can not be modified var

Fourth, exception handling

scala and java as the try catch

Job title:

1. The function can not return a value case, write a function, enter a number from the terminal, print a pyramid.

object Test {
  def main(args: Array[String]): Unit = {
    val line=StdIn.readInt()
    goldenTower(line)
  }
  def goldenTower(column:Int): Unit ={
    for(value<-Range(0,column,1)){
      println(" "*(20-(2*value+1)/2)+"*"*(2*value+1))
    }
  }
}

2. Write a function, from the input terminal 1-9, the print multiplication table 99

  def main(args: Array[String]): Unit = {
    val line=StdIn.readInt()
    multiTable(line)
  }
  def multiTable(column:Int): Unit ={
    for(i<- 1 to column){
      for(j<-1 to i){
        print(s"$j*$i="+j*i+" "*5)
      }
      println()
    }
  }

Guess you like

Origin www.cnblogs.com/littlepage/p/11586660.html