一.函数与代码块

// 函数与代码块
object func_examples {

  // hello是函数的名字    name是函数的参数     第一个String是参数的类型   第二个string的意思是函数返回的类型
  def hello(name:String):String = {
  // 字符串插值
      s"Hello,${name}"
  }                                               //> hello: (name: String)String
  
  //调用这个参数
  hello("yp")                                     //> res0: String = Hello,yp
  
  // 返回结果   自动分配的变量名 res0  返回的结果类型Sting  返回的值是Hello,yp
  
  
  //定义hello的另一张方法
  def hello2(name:String) = {
  // 字符串插值
      s"Hello,${name}"
  }                                               //> hello2: (name: String)String
  
  //函数可以自动推断出函数返回值的类型
    //调用函数hello2
    hello("yp")                               //> res1: String = Hello,yp
    
    def add(x:Int, y:Int) = x+y               //> add: (x: Int, y: Int)Int
    //调用add函数
    //当代码块只有一行时,{}可以省略
    add(1,2)                                  //> res2: Int = 3
}

评论

暂无评论