scala中_的作用

1、初始化时

object Sample {
   var name:String=_
   def main (args: Array[String]){
      name="hello world"
     println(name)
   }
这里的_和null的作用一样

2、引入时

import math._
object Sample {
   def main (args: Array[String]){
    println(BigInt(123))
   }
}
这里的math._相当于math.*

3、集合中使用(最典型,最常用)

object Sample {
   def main (args: Array[String]){
    val newArry= (1 to 10).map(_*2)
   println(newArry)
   }
}
这里的_表示集合中的某一个元素args,foreach中也常用这种表达

4、模式匹配

object Sample {
   def main (args: Array[String]){
     val value="a"
  val result=  value match{
       case "a" => 1
       case "b" => 2
       case _ =>"result"
     }
     println(result)
   }
}
这里的_相当于java中switch-case中的default(others)

还有一种写法,用Some包起来,表示Some中的值非空

object Sample {
  def main (args: Array[String]){
    val value=Some("a")
    val result=  value match{
      case Some(_) => 1
      case _ =>"result"
    }
    println(result)
  }
还有一种表示队列(others)

object Sample {
  def main (args: Array[String]){
    val value=1 to 5
    val result=  value match{
      case Seq(_,_*) => 1
      case _ =>"result"
    }
    println(result)
  }
}
还有一种在scala特有的偏函数中使用(others)

object Sample {
   def main (args: Array[String]){
    val set=setFunction(3.0,_:Double)
     println(set(7.1))
   }
  def setFunction(parm1:Double,parm2:Double): Double = parm1+parm2
}
5、元组Tuple

object Sample {
   def main (args: Array[String])={
     val value=(1,2)
     print(value._1)
   }
}
6、函数准备接收不定长的参数时

object Sample {
   def main (args: Array[String])={
    val result=sum(1 to 5:_*)
     println(result)
   }
  def sum(parms:Int*)={
    var result=0
    for(parm <- parms)result+=parm
    result
  }
}



發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章