For,Function,Lazy

 1 package com.dtgroup.study
 2 import scala.io.Source
 3 
 4 object ForFunctionLazy {
 5   def main(args: Array[String]): Unit = {
 6     // for
 7     println("for:line 0")
 8     for (i <- 1 to 2; j <- 1 to 2) println("i=" + i + ",j=" + j)
 9     println("for:line 1")
10     for (i <- 1 to 2; j <- 1 to 2 if i == j) println("i=" + i + ",j=" + j)
11     println("for:line 2")
12     for (i <- 1 to 2; j <- 1 to 2 if i > j) println("i=" + i + ",j=" + j)
13     println("for:line 3")
14     for (i <- 1 to 2; j <- 1 to 2 if i != j) println("i=" + i + ",j=" + j)
15     // error: for(i<- 1 to 2;j <-1 to 2 if i<>j) println("i="+i+",j="+j)
16 
17     // func: 
18     // 1,)the function with value
19     // 2,)the scala ide known the result type
20     // 3,)in the recursion must declare the result type.
21     def add(x: Int) = x * 2
22     // nickname function
23     val add2 = (x: Int) => x * 200
24     var i = 100;
25     println("func:line 0")
26     println(add(i))
27     println("func:line 1")
28     println(add2(i))
29 
30     def fac(n: Int): Int = if (n <= 0) 1 else n * fac(n - 1)
31     println("func:line 2,The result from a fac is:" + fac(5))
32 
33     // the parameter of function can be assigned value
34     def combine(content: String, left: String = "<", right: String = ">") = left + content + right
35     println("func:line 3,The result from a combine is:" + combine("value"))
36     println("func:line 4,The result from a combine is:" + combine("value", "[", "]"))
37 
38     // param[]
39     def connected(args: Int*) = {
40       var result = ""
41       for (arg <- args) result += "," + arg.toString
42       result
43     }
44 
45     println("func:line 5,The result from a connected is:" + connected(1, 2, 3, 4, 5, 6))
46     // lazy
47 
48     lazy val file = Source.fromFile("d:\\spark2.txt")
49     println("lazy:line 0")
50     for(line <- file.getLines()) println(line)
51     println("lazy:line 1")
52   }
53 }

1,)for 中可以执行嵌套,同时可以加过滤条件;

2,)函数:

  a,)不仅仅有返回值时也是可以不写的,编译器会自动识别类型,但是如果使用在递归函数中必须指明返回值;

  b,)函数是有值的,从匿名函数中可以看出该结论;

  c,)函数的参数可以制定默认值;

  d,)函数的参数可以使用“类型*”,不限制传递参数个数;

3,)Lazy的用法,懒执行,只有当第一次使用时才加载,在scala中,对代码优化有极大贡献。

posted @ 2015-11-16 22:18  cctext  阅读(353)  评论(0编辑  收藏  举报