More beautiful fast orElse infrastructure. Review by extempore.

git-svn-id: http://lampsvn.epfl.ch/svn-repos/scala/scala/trunk@26045 5e8d7ff9-d8ef-0310-90f0-a4852d11357a
This commit is contained in:
odersky 2011-11-22 14:31:40 +00:00
parent e6677eea1c
commit 636f6e0793
2 changed files with 13 additions and 7 deletions

View File

@ -25,7 +25,9 @@ trait PartialFunction[-A, +B] extends (A => B) {
*/
def isDefinedAt(x: A): Boolean
protected def missingCase[A1 <: A, B1 >: B]: PartialFunction[A1, B1] = PartialFunction.empty
//protected def missingCase[A1 <: A, B1 >: B]: PartialFunction[A1, B1] = PartialFunction.empty
protected def missingCase(x: A): B = throw new MatchError(x)
/** Composes this partial function with a fallback partial function which
* gets applied where this partial function is not defined.

View File

@ -8,6 +8,8 @@
package scala.runtime
import scala.annotation.unchecked.uncheckedVariance
/** This class provides a default implementation of partial functions
* that is used for all partial function literals.
* It contains an optimized `orElse` method which supports
@ -21,18 +23,20 @@ abstract class AbstractPartialFunction[-T1, +R]
with PartialFunction[T1, R]
with Cloneable {
private var fallBack: PartialFunction[_, _] = PartialFunction.empty
private var fallBack: PartialFunction[T1 @uncheckedVariance, R @uncheckedVariance] = PartialFunction.empty
override protected def missingCase[A1 <: T1, B1 >: R]: PartialFunction[A1, B1] = synchronized {
fallBack.asInstanceOf[PartialFunction[A1, B1]]
override protected def missingCase(x: T1): R = synchronized {
fallBack(x)
}
// Question: Need to ensure that fallBack is overwritten before any access
// Is the `synchronized` here the right thing to achieve this?
// Is there a cheaper way?
def orElseFast[A1 <: T1, B1 >: R](that: PartialFunction[A1, B1]) : PartialFunction[A1, B1] = {
val result = this.clone.asInstanceOf[AbstractPartialFunction[T1, R]]
result.synchronized { result.fallBack = this.fallBack orElse that }
result
val result = this.clone.asInstanceOf[AbstractPartialFunction[A1, B1]]
result.synchronized {
result.fallBack = this.fallBack orElse that
result
}
}
}