1./**
2. * 定义变量和常量
3. * 变量 :用 var 定义 ,可修改
4. * 常量 :用 val 定义,不可修改
5. */
6. var name = "zhangsan"
7. println(name)
8. name ="lisi"
9. println(name)
10. val gender = "m"
11. // gender = "m"//错误,不能给常量再赋值
1.class Person{
2. val name = "zhangsan"
3. val age = 18
4. def sayName() = {
5. "my name is "+ name
6. }
7.}
1. object Lesson_Class {
2. def main(args: Array[String]): Unit = {
3. val person = new Person()
4. println(person.age);
5. println(person.sayName())
6. }
7.}
object中不可以传参,当创建一个object时,如果传入参数,那么会自动寻找object中的相应参数个数的apply方法。
1./**
2.* Object 相当于单例对象,不能传参
3.* 如果在创建Object时传入参数,那么运行代码时会自动寻找Object中相应参数个数的apply方法
4.*/
5.object LessonObj {
6. def apply(name:String) = {
7. println(s"name is $name")
8. }
9. def apply(name:String,age:Int) = {
10. println(s"name is $name,age is $age")
11. }
12. def main(args: Array[String]): Unit = {
13. LessonObj("zhangsan")
14. LessonObj("zhangsan",18)
15. }
16.}
1.class Person(xname :String , xage :Int){
2. var name = Person.name
3. val age = xage
4. var gender = "m"
5. def this(name:String,age:Int,g:String){
6. this(name,age)
7. gender = g
8. }
9.
10. def sayName() = {
11. "my name is "+ name
12. }
13.
14.}
15.
16.object Person {
17. val name = "zhangsanfeng"
18.
19. def main(args: Array[String]): Unit = {
20. val person = new Person("wagnwu",10,"f")
21. println(person.age);
22. println(person.sayName())
23. println(person.gender)
24. }
25.}
注意点:
重写构造函数的时候,必须要调用默认的构造函数。
1./**
2.* if else
3.*/
4.val age =18
5.if (age < 18 ){
6.println("no allow")
7.}else if (18<=age&&age<=20){
8.println("allow with other")
9.}else{
10.println("allow self")
11.}
1./**
2.* to和until
3.* 例:
4.* 1 to 10 返回1到10的Range数组,包含10
5.* 1 until 10 返回1到10 Range数组 ,不包含10
6.*/
7.
8.println(1 to 10 )//打印 1, 2, 3, 4, 5, 6, 7, 8, 9, 10
9.println(1.to(10))//与上面等价,打印 1, 2, 3, 4, 5, 6, 7, 8, 9, 10
10.
11.println(1 to (10 ,2))//步长为2,从1开始打印 ,1,3,5,7,9
12.println(1.to(10, 2))
13.
14.println(1 until 10 ) //不包含最后一个数,打印 1,2,3,4,5,6,7,8,9
15.println(1.until(10))//与上面等价
16.
17.println(1 until (10 ,3 ))//步长为2,从1开始打印,打印1,4,7
1./**
2.* for 循环
3.*
4.*/
5.for( i <- 1 to 10 ){
6. println(i)
7.}
1.//可以分号隔开,写入多个list赋值的变量,构成多层for循环
2.//scala中 不能写count++ count-- 只能写count+
3.var count = 0;
4.for(i <- 1 to 10; j <- 1 until 10){
5. println("i="+ i +", j="+j)
6. count += 1
7.}
8.println(count);
9.
10.//例子: 打印小九九
11.for(i <- 1 until 10 ;j <- 1 until 10){
12. if(i>=j){
13. print(i +" * " + j + " = "+ i*j+" ")
14. }
15. if(i==j ){
16. println()
17. }
18.
19.}
1.//可以在for循环中加入条件判断
2.for(i<- 1 to 10 ;if (i%2) == 0 ;if (i == 4) ){
3. println(i)
4.}
1.//将for中的符合条件的元素通过yield关键字返回成一个集合
2.val list = for(i <- 1 to 10 ; if(i > 5 )) yield i
3.for( w <- list ){
4. println(w)
5.}
6.
7./**
8.* while 循环
9.*/
10.var index = 0
11.while(index < 100 ){
12. println("第"+index+"次while 循环")
13. index += 1
14.}
15.index = 0
16.do{
17. index +=1
18. println("第"+index+"次do while 循环")
19.}while(index <100 )