Scala _02基础
生活随笔
收集整理的這篇文章主要介紹了
Scala _02基础
小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
Scala基礎(chǔ)
1、數(shù)據(jù)類型
?
2、變量和常量的聲明
- 定義變量或者常量的時(shí)候,也可以寫上返回的類型,一般省略,如:val a:Int = 10
- 常量不可再賦值
3、類和對象
- 創(chuàng)建類
- 創(chuàng)建對象
- 對象中的apply方法
object中不可以傳參,當(dāng)創(chuàng)建一個(gè)object時(shí),如果傳入?yún)?shù),那么會自動尋找object中的相應(yīng)參數(shù)個(gè)數(shù)的apply方法。
package com.henu.scala /*** object單例對象中不可以傳參,* 如果在創(chuàng)建object時(shí)傳入?yún)?shù),那么會自動根據(jù)參數(shù)的個(gè)數(shù)去Object中* 尋找響應(yīng)的apply方法。*/ object ApplyDemo {def apply(s : String) = {println("name is " + s)}def apply(s : String,age : Int) = {println("name is " + s + ",age is " + age)}def main(args: Array[String]): Unit = {ApplyDemo("george")ApplyDemo("george",22)} }- 伴生類和伴生對象
注意點(diǎn):
- if else
- for ,while,do…while
to和until 的用法(不帶步長,帶步長區(qū)別)?
package com.henu.scalaobject ForWhileDoWhileDemo {/*** to和until* 例:* 1 to 10 返回1到10的Range數(shù)組,包含10* 1 until 10 返回1到10 Range數(shù)組 ,不包含10*/def main(args: Array[String]): Unit = {println(1 to 10)//Range(1, 2, 3, 4, 5, 6, 7, 8, 9, 10)println(1 to (10))//Range(1, 2, 3, 4, 5, 6, 7, 8, 9, 10)println(1 to (10,2))//Range(1, 3, 5, 7, 9)println(1.to(10,2))//Range(1, 3, 5, 7, 9)println(1 until 10)//Range(1, 2, 3, 4, 5, 6, 7, 8, 9)println(1 until(10))//Range(1, 2, 3, 4, 5, 6, 7, 8, 9)print(1 until(10,3))//Range(1, 4, 7)} }創(chuàng)建for循環(huán)
/*** for 循環(huán) 打印1-10*/for (i <- 1 to 10){println(i)}創(chuàng)建多層for循環(huán)
//可以分號隔開,寫入多個(gè)list賦值的變量,構(gòu)成多層for循環(huán)//scala中 不能寫count++ count-- 只能寫count+var count = 0//相當(dāng)于雙層的嵌套循環(huán)for (i <- 1 to 10; j <- 1 until 10){println("i=" + i + ", j = " + j)count += 1}println(count)//90//例子:打印乘法表for (i <- 1 until 10; j <- 1 until 10){if (i >= j){print(i + "*" + j + "=" + i*j + " ")}if (i == j){println()}}for循環(huán)中可以加條件判斷,可以使用分號隔開,也可以不使用分號
for (i <- 1 to 10; if (i%2) == 0;if (i == 4)){println(i)}scala中不能使用count++,count只能使用count = count+1 ,count += 1
for循環(huán)用yield 關(guān)鍵字返回一個(gè)集合
while循環(huán),while(){},do {}while()
//將for中的符合條件的元素通過yield關(guān)鍵字返回成一個(gè)集合var list = for (i <- 1 to 10; if (i > 5)) yield ifor (w <- list){println(w)}/*** while循環(huán)*/var index = 0while(index < 100){println("第"+index+"次while循環(huán)")index += 1}println(index)index = 0println("**************************")do {index += 1println("第"+index+"次while循環(huán)")}while(index < 100)?
超強(qiáng)干貨來襲 云風(fēng)專訪:近40年碼齡,通宵達(dá)旦的技術(shù)人生總結(jié)
以上是生活随笔為你收集整理的Scala _02基础的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 大型电商网站的页面静态化方案是如何支撑亿
- 下一篇: Scala _03方法与函数