scala 函式和方法

破棉襖發表於2015-10-30


函式:程式導向時的叫法

方法:物件導向時的叫法


個人理解函式式可在一定場景下使程式碼更加簡潔。


Scala:

  1. scala> val myList = List(3,56,1,4,72)
  2. myList: List[Int] = List(3, 56, 1, 4, 72)

  3. scala> // map()引數是一個函式

  4. scala> myList.map((x) => 2*x)
  5. res15: List[Int] = List(6, 112, 2, 8, 144)

  6. scala> //嘗試給map()函提供一個方法作為引數

  7. scala> def m4(x:Int) = 3*x
  8. m4: (x: Int)Int

  9. scala> //正常執行

  10. scala> myList.map(m4)
  11. res17: List[Int] = List(9, 168, 3, 12, 216)

Java(Lambda):

  1. String[] atp = {"Rafael Nadal", "Novak Djokovic",
  2.  "Stanislas Wawrinka",
  3.  "David Ferrer","Roger Federer",
  4.  "Andy Murray","Tomas Berdych",
  5.  "Juan Martin Del Potro"};
  6. List<String> players = Arrays.asList(atp);
  7.  
  8. // 以前的迴圈方式
  9. for (String player : players) {
  10.  System.out.print(player + "; ");
  11. }
  12.  
  13. // 使用 lambda 表示式以及函式操作(functional operation)
  14. players.forEach((player) -> System.out.print(player + "; "));


來自 “ ITPUB部落格 ” ,連結:http://blog.itpub.net/29754888/viewspace-1819303/,如需轉載,請註明出處,否則將追究法律責任。

相關文章