Scala 入门1(变量、分支循环、函数)
生活随笔
收集整理的這篇文章主要介紹了
Scala 入门1(变量、分支循环、函数)
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
文章目錄
- 1. var 變量,val常量
- 2. 分支、循環
- 3. 函數、方法
- 4. 閉包
學自 https://www.runoob.com/scala/scala-tutorial.html
1. var 變量,val常量
scala 語句 用 ; 或者 \n 分句
object HelloWorld { // 類名跟文件名一致def main(args: Array[String]):Unit = { // Unit 相當于 voidprintln("Hello World!")var myVar : String = "Foo"val myVal : String = "Too"myVar = "hello"// myVal = "world" // val 相當于常量,不能再次賦值val a, b, c = 100 // 不能分別賦值println(a,b,c) //(100,100,100)var pa = (40, "foo")println(pa) // (40,foo)2. 分支、循環
- 跟 java、 c++ 很像
- 特有的 break 方式 Breaks.breakable{}
3. 函數、方法
// val 定義函數, def 定義方法class Test{def method(x:Int) = x + 3 // 多行語句,可用 = {。。。}val func = (x:Int) => x + 3}var obj = new Test()println(obj.method(2)) // 5println(obj.func(2)) // 5// 可變參數def printString(s : String*) = {for(si <- s)println(si)}printString("hello","michael","scala");//指定參數,默認參數def addInt(a:Int, b:Int=2, c:Int=3) : Int = {var sum = 0sum = a+b+cprintln(a,b,c)return sum}println(addInt(1)) // 6// 匿名函數var mul = (x:Int, y:Int) => x*yprintln(mul(3,4))var userDir = () => {System.getProperty("user.dir")}println(userDir())// 偏應用函數是一種表達式,你不需要提供函數需要的所有參數// 只需要提供部分,或不提供所需參數import java.util.Datedef log(date : Date, message : String) = {println(date + "-----" + message)}val date = new Dateval logWithDateBound = log(date, _ : String)logWithDateBound("message1")Thread.sleep(1000)logWithDateBound("message2")Thread.sleep(1000)logWithDateBound("message3")4. 閉包
// 閉包var factor = 3val multi = (i : Int) => i*factorprintln(multi(5)) // 15factor = 2println(multi(5)) // 10} }總結
以上是生活随笔為你收集整理的Scala 入门1(变量、分支循环、函数)的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Java 包及访问权限
- 下一篇: LeetCode 385. 迷你语法分析