From cd696035896fd82c622687107ec4b70cf3f3298e Mon Sep 17 00:00:00 2001 From: Martin Odersky Date: Tue, 22 Nov 2011 14:31:40 +0000 Subject: More beautiful fast orElse infrastructure. --- src/library/scala/PartialFunction.scala | 4 +++- src/library/scala/runtime/AbstractPartialFunction.scala | 16 ++++++++++------ 2 files changed, 13 insertions(+), 7 deletions(-) (limited to 'src') diff --git a/src/library/scala/PartialFunction.scala b/src/library/scala/PartialFunction.scala index 612460d935..ac721b88bc 100644 --- a/src/library/scala/PartialFunction.scala +++ b/src/library/scala/PartialFunction.scala @@ -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. diff --git a/src/library/scala/runtime/AbstractPartialFunction.scala b/src/library/scala/runtime/AbstractPartialFunction.scala index ac68f58b5a..2a45ec3671 100644 --- a/src/library/scala/runtime/AbstractPartialFunction.scala +++ b/src/library/scala/runtime/AbstractPartialFunction.scala @@ -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 + } } } -- cgit v1.2.3