![](https://img.haomeiwen.com/i7007629/928e83aaeee97e7c.png)
一、定义类
scala> class TheQuestion(){
| def theAnswer():Int = {
| return 42;
| }
| }
defined class TheQuestion
scala> val q = new TheQuestion()
q: TheQuestion = TheQuestion@4fdca00a
scala> q.theAnswer
res6: Int = 42
scala> q.theAnswer()
res7: Int = 42
scala>
Singleton Object的定义
scala> object TheQ(){
<console>:1: error: traits or objects may not have parameters
object TheQ(){
^
scala> object TheQ{
| def main(args:Array[String]):Unit={
| val theAnswer:Int = 42
| println(theAnswer)
| val theAnswer2 = 43
| println(theAnswer2)
| }
| }
defined object TheQ
scala> val answer = TheQ.main(null)
42
43
answer: Unit = ()
scala>
注意,对象生成不需要使用new,且定义时候使用object而不是classs
二、几种特殊类型
1、List
List里面的元素是同质的
scala> val list1 = List.range(1,15)
list1: List[Int] = List(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14)
scala> val evenNum = list1.filter((x:Int) => x % 2 ==0)
evenNum: List[Int] = List(2, 4, 6, 8, 10, 12, 14)
scala> val list1 = List(4,2,7,1)
list1: List[Int] = List(4, 2, 7, 1)
scala> val list2 = (1 to 7).toList
list2: List[Int] = List(1, 2, 3, 4, 5, 6, 7)
scala> list1(0)
res27: Int = 4
scala> list1(0)=3
<console>:14: error: value update is not a member of List[Int]
list1(0)=3
scala> val day_of_week =(1 to 7).toList
day_of_week: List[Int] = List(1, 2, 3, 4, 5, 6, 7)
-----------也可以省去括号和点好,但是需要使用postfixOps
scala> import scala.language.postfixOps
import scala.language.postfixOps
scala> val w = 1 to 7 toList
w: List[Int] = List(1, 2, 3, 4, 5, 6, 7)
scala> val w = 1 to 7 toArray
w: Array[Int] = Array(1, 2, 3, 4, 5, 6, 7)
2、Array
Array里面的元素是同质的
arr1: Array[Int] = Array(5, 6, 8, 2, 1, 4)
scala> val arr2:Array[String] = new Array[String](10)
arr2: Array[String] = Array(null, null, null, null, null, null, null, null, null, null)
scala> arr2(0)="first"
scala> arr2
res26: Array[String] = Array(first, null, null, null, null, null, null, null, null, null)
scala> val arr3 = new Array[String](10)
arr3: Array[String] = Array(null, null, null, null, null, null, null, null, null, null)
scala> val day_of_week = (1 to 7).toArray
day_of_week: Array[Int] = Array(1, 2, 3, 4, 5, 6, 7)
-----------Range对象的toArray也可以省去括号和点好,但是需要使用postfixOps
scala> import scala.language.postfixOps
import scala.language.postfixOps
scala> val w = 1 to 7 toArray
w: Array[Int] = Array(1, 2, 3, 4, 5, 6, 7)
3、Set
Set:不可修改(同List)+ 不保证顺序 + 元素不可重复 + 元素可以是不同类型
scala> val set1 = Set(3,4,3,4,3,4,5)
set1: scala.collection.immutable.Set[Int] = Set(3, 4, 5)
4、Tuple
scala> val tuple1 = ("first", 2, 3)
tuple1: (String, Int, Int) = (first,2,3)
scala> tuple1._1
res32: String = first
scala> tuple1._2
res33: Int = 2
scala> tuple1._3
res35: Int = 3
--两个元素的tuple可以使用->语法糖
scala> 1 -> 2
res36: (Int, Int) = (1,2)
scala> 1 -> 2 -> "third"
res37: ((Int, Int), String) = ((1,2),third)
5、Map
不可修改 + key/value元组
scala> val map1 = Map("hello" -> 1, "what"->"house", 3 -> 4)
map1: scala.collection.immutable.Map[Any,Any] = Map(hello -> 1, what -> house, 3 -> 4)
scala> Map("key" -> Map("Key"-> "value"))
res38: scala.collection.immutable.Map[String,scala.collection.immutable.Map[String,String]] = Map(key -> Map(Key -> value))
6、Vector
使用yield 产生一个IndexSeq object. This object translated the value of the result in a Vector
scala> val dayOfWeek = for(i <- 0 to 10) yield {s"$i"}
dayOfWeek: scala.collection.immutable.IndexedSeq[String] = Vector(0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10)
三、循环
1、While 、do...while
var count = 10
while(count > 0){
println(count)
count -=1
}
count = 10
do{
println(count)
count -= 1
}while(count > 0)
2、for
--注意until不包括终点,而to则包含
scala> val arr:Array[String] = new Array[String](10)
arr: Array[String] = Array(null, null, null, null, null, null, null, null, null, null)
scala> for(i <- 0 until arr.length){
| println(arr(i))
| }
null
null
null
null
null
null
null
null
null
null
scala> for(i <- 0 to arr.length-1){
| println(s"value $i is $arr(i)")
| }
value 0 is [Ljava.lang.String;@4e25282d(i)
value 1 is [Ljava.lang.String;@4e25282d(i)
value 2 is [Ljava.lang.String;@4e25282d(i)
value 3 is [Ljava.lang.String;@4e25282d(i)
value 4 is [Ljava.lang.String;@4e25282d(i)
value 5 is [Ljava.lang.String;@4e25282d(i)
value 6 is [Ljava.lang.String;@4e25282d(i)
value 7 is [Ljava.lang.String;@4e25282d(i)
value 8 is [Ljava.lang.String;@4e25282d(i)
value 9 is [Ljava.lang.String;@4e25282d(i)
scala> for(i <- 0 to 20 by 3)
| println(i)
0
3
6
9
12
15
18
--------注意下面for里面的if
scala> val dayOfWeek = for(i <- 0 to 10 if i % 2 == 0) yield {s"$i"}
dayOfWeek: scala.collection.immutable.IndexedSeq[String] = Vector(0, 2, 4, 6, 8, 10)
scala>
四、其他类型
1. String
scala> val strval = "Hello,\nWorld"
strval: String =
Hello,
World
scala> val strval = "Hello,"+"World"
strval: String = Hello,World
scala> val m = """I want
| to say
| Hello world!"""
m: String =
I want
to say
Hello world!
注意跨多行的String的写法
字符串的==操作
scala> val str1 ="hello"
str1: String = hello
scala> val str2 = "hello"
str2: String = hello
scala> val compare = str1 == str2
compare: Boolean = true
interpolation:
----------------------------------------------为了使用interpolation, 我们必须使用the char s
scala> val interpolateVal = "World"
interpolateVal: String = World
scala> val wholeStr = s"Hello ${interpolateVal}"
wholeStr: String = Hello World
scala> println(s"Hello $interpolateVal")
Hello World
scala>
五、条件语句
if:
scala> if(10 % 2 > 0) println("Not a Multiple") else println("Multiple")
Multiple
scala> if(10 % 2 > 0) println("Not a Multiple")
scala>
Pattern Match:
-----------------------------------------------Pattern Matching Expression, 需要使用match关键字
scala> val num1 = 10
num1: Int = 10
scala> val num2 = 20
num2: Int = 20
scala> val max = num1 > num2 match{
| case true => num1
| case false => num2
| }
max: Int = 20
scala> val month ="JAN"
month: String = JAN
scala> val season = month match{
| case "DEC" | "JAN" | "FEB" => "Winter"
| case "MAR" | "APR" | "MAY" => "Spring"
| case "JUN" | "JUL" |"AUG" => "Summer"
| case "SEP" | "OCT" | "NOV" => "Autumn"
| }
season: String = Winter
scala> val season = month match{
| case "DEC" | "JAN" | "FEB" => "Winter"
| case "MAR" | "APR" | "MAY" => "Spring"
| case "JUN" | "JUL" |"AUG" => "Summer"
| case "SEP" | "OCT" | "NOV" => "Autumn"
| case _ => "Not a month"
| }
season: String = Winter
下面这个特别有用,相当与java中原来的instanceof判别
scala> val theAnswer:Int = 42
theAnswer: Int = 42
scala> val anyAnswer:Any = theAnswer
anyAnswer: Any = 42
scala> anyAnswer match {
| case temp:String => "String Value"
| case temp:Int => "Int Value"
| case _ => "Other Value"
| }
res10: String = Int Value
scala>
pattern guard:
------A pattern guard is an if expression to check a Boolean condition used for executing the pattern matching
scala> val emptyStr : String = null
scala> val str = emptyStr match{
| case temp if temp != null => s"Received ${temp}"
| case temp2 => "NULLLLLLLL"
| }
str: String = NULLLLLLLL
scala>
其他杂项
def bubbleSort(arr_input: Array[Int]): Array[Int] =
{
val lastIndex = arr_input.size - 1
for(a <- 1 to lastIndex)
{
for(b <- lastIndex to a by -1)
{
if(arr_input(b) < arr_input(b-1))
{
val temp = arr_input(b)
arr_input(b) = arr_input(b - 1)
arr_input(b - 1 )=temp
}
}
}
arr_input
}
def apply(internal: Int => Int, value:Int) = internal(value)
val addone = (num:Int) => num + 1
val fixValue = () => 9
val theAnswer = () => 42
println(bubbleSort(Array(3,5,2,1))(0))
println(Array(3,4,5)(0))
val arr = Array(3,4,5)
for(a <- 0 to arr.size-1)
{
println(arr(a))
}
3
scala> class F()
defined class F
scala> class G{}
defined class G
scala> val question = new F()
question: F = F@204abeff
scala> val question2 = new G()
question2: G = G@7c51782d
scala>
网友评论