复习Scala基础的小例子
柯里化可参考
http://www.runoob.com/scala/currying-functions.html
隐式转换可参考
http://www.cnblogs.com/MOBIN/p/5351900.html
import scala.collection.mutable.ArrayBuffer
import scala.util.Random
/**
* Created by shaohui on 2017/7/22 0022.
*/
/构造器
class Student(val name:String,val age:Int) {
println("执行主构造器")
try {
println("读取文件")
}catch {
case e:NullPointerException => println("打印异常")
case e:Exception => println("打印异常")
}finally {
println("执行finally部分")
}
private var gender = "male"
def this(name:String,age:Int,gender:String){
this(name,age)
println("执行辅助构造器")
this.gender=gender
}
}
class Queen private(val name: String, prop: Array[String], private var age: Int = 18){
println(prop.length)
//prop被下面的方法使用后,prop就变成了不可变得对象私有字段,等同于private[this] val prop
//如果没有被方法使用该参数将不被保存为字段,仅仅是一个可以被主构造器中的代码访问的普通参数
def description: String = name + " is " + age + " years old with " + prop.toBuffer
}
object Queen{
def main(args: Array[String]) {
val student = new Student("lih",25)
//私有的构造器,只有在其伴生对象中使用
val q = new Queen("hatano", Array("蜡烛", "皮鞭"), 20)
println(q.description)
//单例对象
val session = SessionFactory.getSession
println(session)
}
}
///单例对象
object SessionFactory{
var count = 5
val sessions = new ArrayBuffer[Session]()
while (count>0){
sessions += new Session
count-=1
}
def getSession:Session ={
sessions.remove(0)
}
}
class Session{}
///伴生对象
object Dog {
//伴生对象中的私有属性
private val CONSTANT = "汪汪汪 : "
def main(args: Array[String]) {
val p = new Dog
//访问私有的字段name
p.name = "123"
p.printName()
}
}
class Dog {
val id = 1
private var name = "itcast"
def printName(): Unit ={
//在Dog类中可以访问伴生对象Dog的私有属性
println(Dog.CONSTANT + name )
}
}
//超类的构造
object ClazzDemo {
def main(args: Array[String]) {
val h = new Human
println(h.fight())
}
}
trait Flyable{
def fly(): Unit ={
println("I can fly")
}
def fight(): String
}
abstract class Animal {
def run(): Int
val name: String
}
class Human extends Animal with Flyable{
val name = "abc"
//打印几次"ABC"?
val t1,t2,(a, b, c) = {
println("ABC")
(1,2,3)
}
println(a)
println(t1._1)
//在Scala中重写一个非抽象方法必须用override修饰
override def fight(): String = {
"fight with 棒子"
}
//在子类中重写超类的抽象方法时,不需要使用override关键字,写了也可以
def run(): Int = {
1
}
}
//匹配字符串
object CaseDemo1 extends App{
val arr = Array("Yoshizawa","yuihatano","AoiSola")
val name = arr(Random.nextInt(arr.length))
name match {
case "Yoshizawa" => println("吉泽老师")
case "yuihatano" => println("波多老师")
case _ => println("w我不懂")
}
}
匹配类型
object CaseDemo01 extends App{
//val v = if(x >= 5) 1 else if(x < 2) 2.0 else "hello"
val arr = Array("hello", 1, 2.0, CaseDemo1)
val v = arr(Random.nextInt(4))
println(v)
v match {
case x: Int => println("Int " + x)
case y: Double if y >= 0 => println("Double "+ y)
case z: String => println("String " + z)
case _ => throw new Exception("not match exception")
}
}
///匹配数组、元组
object CaseDemo03 extends App{
val arr = Array(0, 3, 5)
arr match {
case Array(1, x, y) => println(x + " " + y)
case Array(0) => println("only 0")
case Array(0, _*) => println("0 ...")
case _ => println("something else")
}
val lst = List(0)
lst match {
case 0 :: Nil => println("only 0")
case x :: y :: Nil => println(s"x: $x y: $y")
case 0 :: tail => println("0 ...")
case _ => println("something else")
}
val tup = ( 2,3, 7)
tup match {
case (1, x, y) => println(s"1,$x ,$y")
case (_, z, 5) => println(z)
case _ => println("else")
}
}
/7.4. 样例类
case class SubmitTask(id: String, name: String)
case class HeartBeat(time: Long)
case object CheckTimeOutTask
object CaseDemo04 extends App{
val arr = Array(CheckTimeOutTask, HeartBeat(12333), SubmitTask("0001", "task-0001"))
arr(Random.nextInt(arr.length)) match {
case SubmitTask(id, name) => {
println(s"$id, $name")//前面需要加上s, $id直接取id的值
}
case HeartBeat(time) => {
println(time)
}
case CheckTimeOutTask => {
println("check")
}
}
}
//Option类型
object OptionDemo {
def main(args: Array[String]) {
val map = Map("a" -> 1, "b" -> 2)
val v = map.get("b") match {
case Some(i) => i
case None => 0
}
println(v)
//更好的方式
val v1 = map.getOrElse("c", 0)
println(v1)
}
}
///7.6. 偏函数
object PartialFuncDemo {
def func1: PartialFunction[String, Int] = {
case "one" => 1
case "two" => 2
case _ => -1
}
def func2(num: String) : Int = num match {
case "one" => 1
case "two" => 2
case _ => -1
}
def main(args: Array[String]) {
println(func1("one"))
println(func2("one"))
}
}
函数
object FunDemo {
def main(args: Array[String]) {
def f2(x: Int) = x * 2
val f3 = (x: Int) => x * 3
//如果函数名后有:号,则:号到=号之间的部分是函数输入输出声明,=号后为函数体
val f4: (Int) => Int = { x => x * 4 }//函数输入参数为一个Int类型,返回一个Int类型
val f4a: (Int) => Int = _ * 4
val f5 = (_: Int) * 5
val list = List(1, 2, 3, 4, 5)
var new_list: List[Int] = null
//第一种:最直观的方式 (Int) => Int
//new_list = list.map((x: Int) => x * 3)
//第二种:由于map方法知道你会传入一个类型为(Int) => Int的函数,你可以简写
//new_list = list.map((x) => x * 3)
//第三种:对于只有一个参数的函数,你可以省去参数外围的()
//new_list = list.map(x => x * 3)
//第四种:(终极方式)如果参数在=>右侧只出现一次,可以使用_
new_list = list.map(_ * 3)
new_list.foreach(println(_))
var a = Array(1,2,3)
a.map(_* 3)
}
}