时间: 2020-09-19|45次围观|0 条评论

定义有返回值函数

def max(x:Int,y:Int):Int = {
    if(x>y) x
    else y
}

只有一行的情况,可以省略括号。

def max(x:Int,y:Int):Int =if(x>y) x else y
def max(x:Int,y:Int) = if(x>y) x else y

定义无返回值函数

def greeting() = println("hello,world!!!")

如果函数没有参数可以省略括号

def greeting = println("hello,world!!!")

条件表达式

var file = "scala.txt"
if(!args.isEmpty) file = args(0)
println(file)
val file = if(!args.isEmpty) args(0) else "spark.txt"
println(file)
if(!args.isEmpty) args(0) else "spark.txt

while循环与for循环的使用

  def looper(x:Long, y:Long):Long = {
    var a = x
    var b = y
    while(a!=0){
      val temp = a;
      a = a%b
      b= temp
    }
    b
  }
  def looper1(){
    var line = ""
    do{
      line = readLine()
      println("Read:"+line)
    }while(line!="")
  }
    for(i <- 1.to(10)){//i=1~10
      println("Number is :"+i)
    }
    for(i <- 1 to 10){//i=1~10
      println("Number is :"+i)
    }

Scala函数、条件表达式、循环语句插图

原文链接:https://blog.csdn.net/scgaliguodong123_/article/details/49563917

本站声明:网站内容来源于网络,如有侵权,请联系我们,我们将及时处理。

本博客所有文章如无特别注明均为原创。
复制或转载请以超链接形式注明转自起风了,原文地址《Scala函数、条件表达式、循环语句
   

还没有人抢沙发呢~