scala基本语法学习

时间:2022-10-13 15:46:28
package com.ysk

import com.sun.crypto.provider.AESCipher
import com.sun.crypto.provider.AESCipher.AES128_CBC_NoPadding

/**
* Created by Y.S.K on 2017/8/31 in spark02.
*/

object Greeting extends App {
println("welcome ysk")
val v = 1
println(v)

println("hello," + "ysk" + "!")
val x = 10
var y = 20
y += x
print(y)
//lazy val 惰性求值,不会立即求值,会在第一次调用时求值
val a: Byte = 10
val b: Short = 20
val c: Int = 40
val d: Long = 40
val e: Float = 50
val f: Double = 60.98755
val m = true
val n = false
val q = 'x'
val u: Unit = ()
val p = ()

//抛出异常返回nothing
def foo() = throw new Exception("error occurred")

val name = "Y.S.K"
s"my name is ${name}"


def hello(name: String): String = {
s"hello,${name}"
}

hello("Y.S.K")

def hello1(name: String) = {
s"hello,${name}"
}

hello1("Y.S.K")

def add(x: Int, y: Int) = {
x + y
}

add(1, 2)

val l = List("ysk", "ysk2", "ysk3")
for {
s <- l //generator
} println(s)
for {
s <- l
if (s.length > 3) //filter
} println(s)

val result_for = for {
s <- l
s1 = s.toUpperCase()
if (s1 != "")
} yield (s1) //满足则放到新的collection

val result_try = try {
Integer.parseInt("dog")
} catch {
case _: Throwable => 0
} finally {
println("always be printed")
}
val code = 1
val result_match = code match {
case 1 => "one"
case 2 => "two"
case _ => "others"
}

//所有运算基于表达式
def test1(x: Int, y: Int) = {
x * x
}

def test2(x: => Int, y: => Int) = {
x * x
}

//先求实参,然后调用方法call by value
test1(3 + 4, 8)
//先调用方法,如果需要求实参,则求实参,否则不求call by Name
test2(3 + 4, 8)
test1(7, 2 * 4)
test2(7, 2 * 4)

//递归函数,没有循环语句
def bar(x: Int, y: => Int) = 1

def loop(): Int = loop

bar(1, loop)

def factorial(n: Int): Int =
if (n <= 0) 1
//最后调用递归函数
else n * factorial(n - 1)

//尾递归优化
@annotation.tailrec
def factorial2(n: Int, m: Int): Int =
if (n <= 0) 1
//最后调用递归函数
else factorial2(n - 1, m * n)

// bar(loop, 1)


//高阶函数
//函数可作为变量
// val aa=(name:String)=> {"Y.S.K"}
var greeting = (name: String) => {
"hello, " + name
}
greeting(Y.S.K)
//柯里化
def curriedAdd(a: Int)(b: Int) = a + b

curriedAdd(2)(2)
val addOne = curriedAdd(1) _
addOne(2)
}