scala学习——(1)scala基础(上)
- scala> val x = 1 x: Int = 1
一、值与变量
- 值(val):赋值后不可变
val值名称:类型 = XXX
- 变量(var):赋值后可以改变
var变量名称:类型 = XXX
scala> val x : Int = 1
x: Int = 1
scala> x = 2
<console>:12: error: reassignment to val
x = 2
^
scala> var x : Int = 1 x: Int = 1 scala> x = 2 x: Int = 2
scala> val x = 1
x: Int = 1
scala> var x = 1
x: Int = 1
二、常用的类型:
- Byte
- char
- Short
- Int
- Long
- Float
- Double
- Booleal
并无基本类型与包装类型之分
三、方法定义
def 方法名(参数名:参数类型):返回类型={
//block内最后一行为返回值
}
注:当返回值为unit时,可以定义为:
def 方法名(参数名:参数类型){
}
package week1 /** *Create by wucy on 2017/2/8 */ object WeekOne{ def add(x:Int,y:Int): Int = { x+y } def add() = { println("say hello") } def main(args:Array[String]){ println(add(1,2)) add() } }
方法的注意:
- 没有参数的方法可以不带圆括号访问
- Scala没有静态方法,通过object来实现
scala> 1.to(10) res0: scala.collection.immutable.Range.Inclusive = Range 1 to 10 scala> 1 to 10 res1: scala.collection.immutable.Range.Inclusive = Range 1 to 10
- 条件表达式(if)
- 循环表达式(for,while,to,until,Range没有coninue与break)
- 语句终止(分行写时可以不用分号)
scala> if (x>0) 1 else -1 res2: Int = 1 scala> val a = if(x>0) 1 else -1 a: Int = 1
scala> 1 to 10 res3: scala.collection.immutable.Range.Inclusive = Range 1 to 10 scala> 1 until 10 res4: scala.collection.immutable.Range = Range 1 until 10
scala> Range(1,10) res5: scala.collection.immutable.Range = Range 1 until 10 scala> Range(1,10,2) res6: scala.collection.immutable.Range = inexact Range 1 until 10 by 2
def main(args:Array[String]){ //println(add(1,2)) //add() for (i<- 1 to 10){ println(i) } }
scala> for( i<- 1 until 10) println(i) 1 2 3 4 5 6 7 8 9
scala> for( i<- 1 until 10 if i % 2 ==0 ) println(i) 2 4 6 8
- Lazy value(懒加载)
lazy val val_name = val_value
用到时才会去初始化
scala> val a = 1 a: Int = 1 scala> lazy val a = 1 a: Int = <lazy> scala> a res9: Int = 1
- 默认参数
- 带名参数(赋值顺序可以定义时顺序不一致)
- 边长参数(:_*)
四、异常处理
资料来源:小象学院 陈 超 仅供学习研究