2011年5月3日 星期二

3-12. method 宣告

method 宣告,Java 使用的格式是
  type method_name(param1, param2, ...) {
    ...
  }

1. 參數的宣告方式與變數宣告方式相同,格式為 type var_name。
2. Java 使用 return statement 來結束 method 並傳回 return 值。若宣告 void 的 method,不可有 return statement。

請看實際程式案例
class J1 {
  String sayHello(String name) {
    return "Hello " + name;
  }
}

在 Scala 中宣告 method 的方式為:
  def method_name(param1, param2, ...): type = {
    ...
  }

關於 Scala 宣告 method 的重點如下:
1. 使用 def 說明要宣告一個 method
2. 冒號後的 type 是 method 的 return type
3. 可省略 return type,此時 compiler 將會使用 type inference,推論 method 的 return type
4. 若 method 使用到 recursion,method 的 return type 不可使用省略(即,return type inference 不能使用在 recursive method 中)
5. 若使用 return statement 來傳回值,return type 不能推論,因此 return type 不可省略
6. method 宣告後的等號表示「把後面的 code block 設定給本 method」,函數宣告使用等號在函數式語言中非常常見,表明在該函數等於後面的 code block
7. method 後面的等號通常不能省略,但為維持與 Java 類似的格式,所以有時省略。當省略等號時視同宣告該 method 的 return type 為 Unit(沒有 return 值)。
8. 省略等號通常容易導致誤會,不是好習慣,建議等號永遠都不要省略。
9. method 一般使用最後執行到的 statement 作為本 method 最後的傳回值。但也可使用 return 作為 method 結束並傳回值,但並不建議使用 return statement 結束 method 並傳回值。
10. 參數宣告與變數宣告方式相同,格式 var_name: type。method 中參數的 type 一定要有,參數無法使用 type inference。
11. 若 code block 只有一個 statement,可以省略大括號 { 與 },這樣看起來會比較像函數宣告
例:
class S1 {
  def sayHello(name: String): String =  {
    "Hello " + name
  }
}

範例:code block 只有一個 statement時,可以省略大括號 { 與 }
class S1 {
  def sayHello(name: String): String =  "Hello " + name //省略大括號
}
範例:return type 推論
class S1 {
  def sayHello(name: String) =  { //省略 return type,compiler自行推論,本例推論出來為 return String
    "Hello " + name
  }
}
範例:使用 recursive,不可推論 return type
class S1 {
  def sayHello(name: String) = sayHello("Hello " + name)
                  //省略 return type,想要做 return type inference,但出錯
}


範例:參數需指明 type,不可使用 type inference
class S1 {
  def sayHello(name) = Hello " + name //省略參數 type,想要做 type inference,但出錯
}

範例:使用 return statement,需要宣告 return type
class S1 {
  def sayHello(name: String) = {
    return Hello " + name // 使用 return statement,method 的 return type 不可省略
  }
}


範例:省略等號,視同宣告 method 的 return type 為 Unit
class S1 {
  def sayHello(name: String) {//省略等號,視同宣告 return type 為 Unit,雖使用 return statement,來 return String,但 method 的 return type 仍然為 Unit
    return Hello " + name 
  }
}
上例是熟 Java 者常犯的錯誤,因為熟 Java 者常忘記 method 後面等號,又以為會使用 return type inference,所以以為上例的 return type 為 String,其實真正為 Unit。上例並不會引發 compiler 錯誤。
範例:省略等號,視同宣告 method 的 return type 為 Unit,但若又宣告 return type
class S1 {
  def sayHello(name: String): String {//省略等號,視同宣告 return type 為 Unit,但又宣告 return type,引發錯誤
    return Hello " + name 
  }
}


宣告 method 請依照下列 guideline 比較不會有問題:
1. 一定要使用等號,使用等號是好習慣
2. 參數要有 type
3. recursive method 需要宣告 type
4. 不要使用 return statement 來結束執行並傳回值,使用最後一個 statement 是 method 傳回值的原則

沒有留言:

張貼留言