首页  

scala函数定义及使用     所属分类 scala 浏览量 507
需给出所有参数的类型 返回值的类型可选 ,自动推断
递归函数 必须有 返回值类型
默认参数 命名参数 变长参数

def functionName ([list of parameters]) : [return type] = {
    function body
    return [expr]
}

def add1(x:Int,y:Int):Int={
      return x+y
}


def add2(x:Int,y:Int)={
      x+y
}

def add3(x:Int,y:Int)=x+y


def hello1():Unit={
    println("hello")
}
def hello2():Unit=println("hello")
def hello3()=println("hello")

def hello4 = println("hello")
hello4 调用不能带小括号

hello1 hello2 hello3 调用可以不带小括号

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


def displayInfo(name:String,age:Int=9) = println(s"name=$name,age=$age")

displayInfo("cat")
displayInfo("cat",3)

displayInfo(age=7,name="tiger")

命名参数 ,参数可以乱序


def sum(nums:Int *) = {
  var s = 0
  for(e <- nums) s += e
  s
}
sum(1,2,3)



无返回值 Unit 过程 def sayHello(name:String) = println("hello "+name) def sayHello2(name:String) {println("hello "+name)} 无返回值 过程 不用等号 lazy值 如果将一个变量声明为lazy,则只有在第一次使用该变量时,变量对应的表达式才会发生计算, 这种特性对特别耗时的计算操作特别有用, 打开文件进行IO,进行网络IO等 import scala.io.Source._ lazy val lines = fromFile("xxx").mkString println(lines) 使用lazy ,文件不存在,不会报错, 只有在使用变量时才会去读取报错 val lines = fromFile("xxx").mkString

上一篇     下一篇
play scala hello world tutorial

Scala 下划线的用途

scala 匿名函数

play框架web编程实例

scala 大括号省略

scala 表达式/代码块 当参数