scala变量和函数

函数 

package demo

object Demo10 {
  private var num:Option[String] = None
  def s(x:String):Int = x match {
    case "1" =>
      1
    case "2"=>
      2
    case _ =>
      3
  }
  def sc:String = num match {
    case None =>
      val name = "haha"
      num = Some(name)
      num.get
    case Some(a) =>
      println("lala")
      a
  }
  def main(args:Array[String]){
    println(num)  //第一次为None
    println(sc)   //调用函数sc赋值
    println(s("1"))
    println(sc)   //第二次不为None
    println(num)  //输出
  }
}

结果:

None
haha
1
lala
haha
Some(haha)

变量

package demo

object Demo10 {
  private var num:Option[String] = None
  def s(x:String):Int = x match {
    case "1" =>
      1
    case "2"=>
      2
    case _ =>
      3
  }
  var sc:String = num match {
    case None =>
      val name = "haha"
      num = Some(name)
      num.get
    case Some(a) =>
      println("lala")
      a
  }
  def main(args:Array[String]){
    println(num)  
    println(sc)   
    println(s("1"))
    println(sc)   
    println(num)  
  }
}

结果

Some(haha)
haha
1
haha
Some(haha)
相关文章
相关标签/搜索