Scala声明变量、常用类型、条件表达式、块表达式、循环

一、 Scala基础

1. 声明变量

package cn.toto.scala

/**
  * Created by toto on 2017/6/27.
  */
object VariableDemo {
  def main(args: Array[String]): Unit = {
    //使用val定义的变量值是不可变的,相当于java里用final修饰的变量,不可以再改变参数的值
    val i = 1
    println("参数i的值是:" + i)
    //使用var定义的变量是可变的,在scala中鼓励使用val
    var s = "hello";
    println("参数s的值是:" + s)
    //修改一下s的值
    s = "hello word";
    println("修改后的参数s的值是:" + s)
    //Scala编译器会自动推断变量的类型,必要的时候可以指定类型
    //变量名在前,类型在后
    val str : String = "toto";
    println("带有参数类型说明的变量str的值是:" + str);
  }
}

运行结果:

参数i的值是:1
参数s的值是:hello
修改后的参数s的值是:hello word
带有参数类型说明的变量str的值是:toto

2. 常用类型
Scala和Java一样,有7种数值类型Byte、Char、Short、Int、Long、Float和Double(无包装类型)和一个Boolean类型
3. 条件表达式
Scala的的条件表达式比较简洁,例如:

package cn.toto.scala

/**
  * Created by toto on 2017/6/27.
  */
object ConditionDemo {
  def main(args: Array[String]): Unit = {
    val x = 1
    //判断x的值,将结果赋给y
    val y = if(x > 0) 1 else -1
    //打印y的值
    println(y)

    //支持混合类型表达式
    val z = if(x > 1) 1 else "error"
    //打印z的值
    println(z)

    //如果缺失else,相当于if(x > 2) 1 else ()
    val m = if(x > 2) 1
    println(m)

    //在scala中每个表达式都有值,scala中有个Unit类,写做(),相当于Java中的void
    val n = if(x > 2) 1 else ()
    println(n)

    //If和else if
    val k = if(x < 0) {
      0
    } else if(x >= 1) {
      1
    } else {
      -1
    }
    println(k);
  }
}

运行结果:

1
error
()
()
1

4. 块表达式

package cn.toto.scala

/**
  * Created by toto on 2017/6/27.
  */
object BlockExpressionDemo {
  def main(args: Array[String]): Unit = {
    val x = 0
    //在scala中的{}中可包含一系列表达式,快中最后一个表达式的值就是块的值,下面就是一个块表达式
    val result = {
      if(x < 0) {
        -1
      } else if(x >= 1) {
        1
      } else {
        "error"
      }
    }

    //result的值就是块表达式的结果
    println(result)
  }
}

运行结果:
error

5. 循环
在scala中有for循环和while循环,用for循环比较多
for循环语法结构:for (i <- 表达式/数组/集合)

package cn.toto.scala

/**
  * Created by toto on 2017/6/27.
  */
object ForDemo {
  def main(args: Array[String]): Unit = {
    //for(i <- 表达式),表达式1 to 10返回一个Range(区间)
    //每次循环将区间中的一个值赋给i
    for(i <- 1 to 10) {
      print(i + " ")
    }

    println("")

    //for(i <- 数组)
    val arr = Array("a","b","c")
    for(i <- arr) {
      print(i + " ");
    }

    println("")

    //高级for循环
    //每个生成器都可以带一个条件,注意:if前面没有分号
    for(i <- 1 to 3; j <- 1 to 3 if i != j) {
      print((10 * i + j) + " ")
    }
    println()

    //for推导式:如果for循环的循环体以yield开始,则该循环会构建出一个集合
    //每次迭代生成集合中的一个值
    val v = for(i <- 1 to 10) yield i * 10
    println(v)
  }
}

运行结果:

1 2 3 4 5 6 7 8 9 10 
a b c 
12 13 21 23 31 32 
Vector(10, 20, 30, 40, 50, 60, 70, 80, 90, 100)
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

涂作权的博客

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值