scala 函数和方法


函数:面向过程时的叫法

方法:面向对象时的叫法


个人理解函数式可在一定场景下使代码更加简洁。


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/,如需转载,请注明出处,否则将追究法律责任。

转载于:http://blog.itpub.net/29754888/viewspace-1819303/

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值