Scala的Pattern Matching Anonymous Functions

参考自http://stackoverflow.com/questions/19478244/how-does-a-case-anonymous-function-really-work-in-scala

http://www.scala-lang.org/files/archive/nightly/pdfs/ScalaReference.pdf

http://docs.scala-lang.org/overviews/core/futures.html

在第三篇文档《Futures and Promises》中,讲到了Future对象有三个方法可以注册callback

import scala.util.{Success, Failure}

val f: Future[List[String]] = future {
  session.getRecentPosts
}

f onComplete {
  case Success(posts) => for (post <- posts) println(post)
  case Failure(t) => println("An error has occured: " + t.getMessage)
}

f onFailure {
  case t => println("An error has occured: " + t.getMessage)
}

f onSuccess {
  case posts => for (post <- posts) println(post)
}

传给onComplete、onFailture和onSuccess的都是

{ case p1 => b1 ... case pn => bn }

形式的语句,但是这三个方法接受的参数类型却是不同的。

abstract def onComplete[U](f: (Try[T]) ⇒ U)(implicit executor: ExecutionContext): Unit

def onSuccess[U](pf: PartialFunction[T, U])(implicit executor: ExecutionContext): Unit

def onFailure[U](pf: PartialFunction[Throwable, U])(implicit executor: ExecutionContext): Unit

onCompelete的参数类型的是一个 (Try[T]) => U函数, 而onSuccess和onFailure的参数类型是偏函数。

那么,问题来了……{ case p1 => b1 ... case pn => bn } 的类型到底是啥呢?

在<The Scala Language Specification>的第8.5章给出了说明:

An anonymous function can be defined by a sequence of cases

{case p1 =>b1 ...case pn =>bn }

which appear as an expression without a prior match.
The expected type of such an expression must in part be defined. It must be either scala.Functionk[S1, ..., Sk, R] for some k >0, or scala.PartialFunction[S1, R], where the argument type(s) S1, ..., Sk must
be fully determined, but the result type R may be undetermined.

也就是说{ case p1 => b1 ... case pn => bn } 这种表达式的值的类型可以有两种,要不是一个函数,要不是一个偏函数(偏函数也是一种函数)。在这个表达式的位置上需要哪种类型,编译器就会用这个表达式生成对应的类型。但是无论是生成函数还是偏函数,它们的参数的类型都必须是确定的,对于一个特定的Future对象,onComplete接受的函数的参数类型是Try[T],而onSuccess接受的PartialFunction的参数类型是T,onFailure接受的PartialFunction的参数类型是Throwable。但是这些函数的返回类型U可以不是需要这个{ case p1 => b1 ... case pn => bn } 表达式的地方指定的。比如,这三个onXXX方法都没有指定它所接受的函数的返回值类型。

例子:

import java.io.IOException

import scala.concurrent._
import scala.concurrent.ExecutionContext.Implicits.global
import scala.util.Success
import scala.util.Failure

object CallbacksOfFuture extends App {

  def getRecentPosts = {
    Thread.sleep(5000)
    "Good morning" :: "Good afternoon" :: Nil
    throw new TimeoutException("Goodbye")
  }

  val f: Future[List[String]] = future {
    val posts = getRecentPosts
    posts
  }
  f onComplete {
    case Success(posts) => posts.foreach(println)
    case Failure(e) => println("An error has occured: " + e.getMessage)
  }

  f onComplete { result =>
    result match {
      case Success(posts) => posts.foreach(println)
      case Failure(e) => println("An error has occured: " + e.getMessage)
    }
  }

  //won‘t compile

//  f onComplete{
//    case 1 => 2
//  }

  f onSuccess {
    case posts => posts foreach println
  }

  f onFailure{
    case r: IOException => println("got IOException: " + r.getMessage)
    case r: TimeoutException => println("got TimeoutException: " + r.getMessage)
    case e => println("An error has occured: " + e.getMessage)
  }

  f flatMap{ posts => future{posts}} foreach(println)
  f map (posts => posts) foreach println

  Thread.sleep(10000)
}
时间: 2024-08-30 03:01:13

Scala的Pattern Matching Anonymous Functions的相关文章

Beginning Scala study note(5) Pattern Matching

The basic functional cornerstones of Scala: immutable data types, passing of functions as parameters and pattern matching. 1. Basic Pattern Matching In Scala, your cases can include types, wildcards, sequences, regular expressions, and so forth. scal

[Scala] Pattern Matching(模式匹配)

Scala中的match, 比起以往使用的switch-case有著更強大的功能, 1. 傳統方法 def toYesOrNo(choice: Int): String = choice match { case 1 => "yes" case 0 => "no" case _ => "error" } // toYesOrNo(1)=>"yes" // toYesOrNo(0)=>"n

Scala 函数式程序设计原理(4)--Types and Pattern Matching

4.1 Objects Everywhere Pure Object Orientation: A pure object-oriented language is one in which every value is an object. If the language is based on classes, this means that the type of each value is a class. 4.2 Functions as Objects (x: Int) => x *

Programming in Scala (Second Edition) 读书笔记15 case class and pattern matching

一个算术表达式包含: 数字,变量,二元操作符,一元操作符.用下面几个类来模拟它们 package chapter15 abstract class Expr case class Var(name: String) extends Expr case class Number(num: Double) extends Expr case class UnOp(operator: String, arg: Expr) extends Expr case class BinOp(operator: 

Scala Learning(1): 使用Pattern Matching表达JSON

这是一个挺能展现Scala编程方式的例子,对正在熟悉Scala这门语言的开发者很有帮助. Representing JSON 用Scala来表达JSON(Java Script Object Notation)结构, { "firstname" : "John", "lastname" : "Smith", "address" : { "street" : "21 2nd St

scala pattern matching

scala语言的一大重要特性之一就是模式匹配.在我看来,这个怎么看都很像java语言中的switch语句,但是,这个仅仅只是像(因为有case关键字),他们毕竟是不同的东西,switch在java中,只能是用在函数体类的,且需要结合break使用.但是,在scala语言中,pattern matching除了有case关键字,其他,似乎和java又有很多甚至完全不同的东西. scala在消息处理中为模式匹配提供了强大的支持! 下面看看模式匹配的英文定义: A pattern match incl

Postgresql - Pattern Matching

There are three separate approaches to pattern matching provided by PostgreSQL: the traditional SQL LIKE operator, the more recent SIMILAR TO operator (added in SQL:1999), and POSIX-style regular expressions. Aside from the basic "does this string ma

Functional PHP 5.3 Part I - What are Anonymous Functions and Closures?

One of the most exciting features of PHP 5.3 is the first-class support for anonymous functions. You may have heard them referred to as closures or lambdas as well. There's a lot of meaning behind these terms so let's straighten it all out. What is t

Codeforces Round #504 (rated, Div. 1 + Div. 2, based on VK Cup 2018 Final) A. Single Wildcard Pattern Matching B. Pair of Toys C. Bracket Subsequence D. Array Restoration-区间查询最值(RMQ(ST))

Codeforces Round #504 (rated, Div. 1 + Div. 2, based on VK Cup 2018 Final) A. Single Wildcard Pattern Matching 题意就是匹配字符的题目,打比赛的时候没有看到只有一个" * ",然后就写挫了,被hack了,被hack的点就是判一下只有一个" * ". 1 //A 2 #include<iostream> 3 #include<cstdio&g