Scala函數(shù)的使用
1、定義
def 方法名(參數(shù)名: 參數(shù)類型): 返回值類型 = {//方法體}
/**
* @author Gjing
**/
object Test {
def main(args: Array[String]): Unit = {
sayHello("Hello")
}
def sayHello(text: String):Unit = {
println(text)
}
}
如果你不寫等于號和方法主體,那么方法會被隱式聲明為抽象(abstract),包含它的類型于是也是一個抽象類型。
2、默認(rèn)值
調(diào)用方法時如果為傳參,則會使用默認(rèn)值
/**
* @author Gjing
**/
object Test {
def main(args: Array[String]): Unit = {
sayWorld()
}
def sayWorld(text: String = "World"):Unit = println(text)
}
3、命名參數(shù)
可通過參數(shù)名指定你當(dāng)前設(shè)置的值是哪一個參數(shù)
/**
* @author Gjing
**/
object Test {
def main(args: Array[String]): Unit = {
nameTest(text1 = "hello",text2 = "world")
}
def nameTest(text1: String, text2:String): Unit = {
println(text1, text2)
}
}
4、可變參數(shù)
不限制參數(shù)的數(shù)量,如Java1.5出現(xiàn)的...
/**
* @author Gjing
**/
object Test {
def main(args: Array[String]): Unit = {
varTest(1,2,3,4)
}
def varTest(a: Int*):Unit = println(a)
}
5、條件表達(dá)式
和java類似
object Test {
def main(args: Array[String]): Unit = {
if (1 == 1) println(true) else println(false)
}
}
6、循環(huán)表達(dá)式
在循環(huán)時很多時候會用到區(qū)間,scala提供了兩種方式,分別為to和until, to關(guān)鍵字會包含右邊的值,比如1 to 10,此時循環(huán)輸出會是1-10;until不包含, 循環(huán)輸出會是1-9
a、while
運(yùn)行一系列語句,如果條件為true,會重復(fù)運(yùn)行,直到條件變?yōu)閒alse
object Test {
def main(args: Array[String]) {
// 局部變量
var a = 10;
// while 循環(huán)執(zhí)行
while( a < 20 ){
println( "Value of a: " + a );
a = a + 1;
}
}
}
b、for
用來重復(fù)執(zhí)行一系列語句直到達(dá)成特定條件達(dá)成,一般通過在每次循環(huán)完成后增加計數(shù)器的值來實現(xiàn)
object Test {
def main(args: Array[String]) {
// for 循環(huán)
for( a <- 1 to 10){
println( "Value of a: " + a );
}
}
}
c、do while
條件表達(dá)式出現(xiàn)在循環(huán)的尾部,所以循環(huán)中的 statement(s) 會在條件被測試之前至少執(zhí)行一次
object Test {
def main(args: Array[String]) {
// 局部變量
var a = 10;
// do 循環(huán)
do{
println( "Value of a: " + a );
a = a + 1;
}while( a < 20 )
}
}