练习目标:
熟悉scala 基础语法
- 一周掌握 scala入门知识
学习内容:
- 基本语法
- 条件语句
- 循环语句
代码记录:
package scala_test
import java.io.{FileNotFoundException, FileReader, IOException}
import scala.annotation.tailrec
class scala_test {
def addint(a: Int, b: Int): Int = {
var sum = 0
sum = a + b
return sum
}
//传名调用
def time() = {
println("获取时间,单位为纳秒")
System.nanoTime()
}
def delayed(t: => Long) = {
println("在delayed方法内")
println("参数:" + t)
t
}
//可变参数
def printstring(args: String*): Unit = {
var i: Int = 0
for (arg <- args) {
println("arg Value [" + i + "] = " + arg)
i = i + 1
}
}
//递归函数
def factorial(n: BigInt): BigInt = {
if (n <= 1) {
1
} else {
n * factorial(n - 1)
}
}
//高阶函数
def apply(f: Int => String, v: Int) = f(v)
def layout[A](x: A) = "[" + x.toString + "]"
//嵌套函数
def factorial1(i: Int): Int = {
@tailrec
def fact(i: Int, accumulator: Int): Int = {
if (i <= 1) {
accumulator
} else {
fact(i - 1, i * accumulator)
}
}
fact(i, 1)
}
//函数柯里化
def add(x: Int)(y: Int) = x + y
//闭包
var factor = 3
val mutilplier = (i: Int) => i * factor
//数组
var z = new Array[String](3)
z(0) = "hello"
z(1) = "world"
z(2) = "!"
//集合:列表
val site = "Runoob" :: ("Google" :: ("Baidu" :: Nil))
val nums = Nil
//集合:map
var A: Map[Char, Int] = Map()
val colors = Map("red" -> "#FF0000", "azure" -> "#F0FFFF")
val sites = Map("runoob" -> "http://www.runoob.com",
"baidu" -> "http://www.baidu.com",
"taobao" -> "http://www.taobao.com")
def err_test(): Unit = {
try {
var str="E:\\java_work\\maven_scala\\src\\main\\resources\\"
val f = new FileReader("input.txt")
} catch {
case ex: FileNotFoundException => {
println("Missing file exception")
}
case ex: IOException => {
println("IO Exception")
}
}
}
}