Scala高阶编程指南

Scala高阶函数

  • Scala高阶函数
    • 高阶函数
    • SAM转换
    • Curring
  • 模式匹配
    • 基本Type
    • ArrayListTuple
    • Case Class
    • 提取器
    • Option

高阶函数

(1 to 9).map("*" * _).foreach(println _)
println((1 to 9).reduceLeft(_ * _))
"Spark is the most exciting thing happening in big data today".split(" ")
.sortWith(_.length < _.length).foreach(println)

//传入参数Double => Double函数的高阶函数 
def high_order_functions(f: Double => Double) = f(0.25) println(high_order_functions(ceil _)) println(high_order_functions(sqrt _)) //简化传入函数过程 high_order_functions((x: Double) => 3 * x) high_order_functions((x) => 3 * x) high_order_functions(x => 3 * x) high_order_functions(3 * _) val fun2 = 2 * (_: Double) val fun3: (Double) => Double = 3 * _

SAM转换

var data = 0
val frame = new JFrame("SAM Testing");
val jButton = new JButton("Counter")

jButton.addActionListener((event: ActionEvent) => {data += 1; println(data)})

//通过隐式转换
implicit def function(action: (ActionEvent) => Unit) = new ActionListener { override def actionPerformed(event: ActionEvent) { action(event) } } frame.setContentPane(jButton); frame.pack(); frame.setVisible(true); 

Curring

//柯里话
def multiple(x: Int, y: Int) = x * y def multipleOne(x: Int) = (y: Int) => x * y println(multipleOne(6)(7)) //数组内容比较 val a = Array("Hello", "Spark") val b = Array("hello", "spark") println(a.corresponds(b)(_.equalsIgnoreCase(_)))

模式匹配

基本Type

//匹配作用域要从小到大
val data =2
data match {
    case 1 => println("First")
    case 2 => println("Second")
    case _ => println("Not Known Number")
}

//result = data => case "Something"
val result = data match {
    case i if i == 1 => "The First"
    case number if number ==2 => "The Second" + number
    case _ => "Not Known Number"
}

"Hello World!".foreach { c => print(
        c match{
          case ' ' => "space"
          case ch => "Char: " +ch
        }
)}

Array、List、Tuple

//Array模式匹配
def match_array(arr : Any) = arr match { case Array(0) => println("Array:" + "0") case Array(x, y) => println("Array:" + x + " " +y) case Array(0, _*) => println("Array:" + "0 ...") case _ => println("something else") } match_array(Array(0)) //Array:0
match_array(Array(0,1))                 //Array:0 1
match_array(Array(0,1,2,3,4,5))         //Array:0 ...

//List模式匹配        
def match_list(lst : Any) = lst match { case 0 :: Nil => println("List:" + "0")
    case x :: y :: Nil => println("List:" + x + " " + y)
    case 0 :: tail => println("List:" + "0 ...")
    case _ => println("something else")
}

match_list(List(0))                     //List:0     
match_list(List(3,4))                   //List:3 4
match_list(List(0,1,2,3,4,5))           //List:0 ...

//Tuple模式匹配
def match_tuple(tuple : Any) = tuple match { case (0, _) => println("Tuple:" + "0") case (x, 0) => println("Tuple:" + x ) case _ => println("something else") } match_tuple((0,"Scala")) //Tuple: 0
match_tuple((2,0))                      //Tuple: 2
match_tuple((0,1,2,3,4,5))              //Something else

Case Class

//定义person以及case class abstract class Person case class Student(age: Int) extends Person case class Worker(age: Int, salary: Double) extends Person case object Shared extends Person //class匹配 def caseOps(person: Person) = person match { case Student(age) => println("I am " + age + "years old") case Worker(_, salary) => println("Wow, I got " + salary) case Shared => println("No property") } caseOps(Student(19)) caseOps(Shared) val worker = Worker(29, 10000.1) val worker2 = worker.copy(salary = 19.95) println(woker2.salary) val worker3 = worker.copy(age = 30) println(worker3.age) //嵌套的case class abstract class Item case class Book(description: String, price: Double) extends Item case class Bundle(description: String, price: Double, items: Item*) extends Item def caseclass_nested(person: Item) = person match { //@引用后面对象 case Bundle(_, _, art @ Book(_, _), rest @ _*) => println(art.description + " : " + art.price) case Bundle(_, _, Book(descr, _), _*) => println("The first description is :" + descr) case _ => println("Oops!") } caseclass_nested(Bundle("1111 Special's", 30.0, Book("Scala for the Spark Developer", 69.95), Bundle("Hadoop", 40.0, Book("Hive", 79.95), Book("HBase", 32.95) ) )) caseclass_nested(Bundle("1212 Special's", 35.0, Book("Spark for the Impatient", 39.95) )) 

提取器

val str = "20150628 scala"
val pattern = "([0-9]+)([a-z]+)".r

str match {
    case pattern (num, item) => println(num + " " + item)
}

Option

val socores = Map("Java" -> 10,"Scala" -> 20)

socores.get("Java") match {
    case Some(name) => println(name)
    case None => println("No socore")
}

你可能感兴趣的:(scala)