From 9f6fe27b218039362ce72d90e548e06eed323dc7 Mon Sep 17 00:00:00 2001 From: Paul Phillips Date: Fri, 5 Jun 2009 14:36:36 +0000 Subject: Altered GenericRange contains to do something l... Altered GenericRange contains to do something less useless when trying to cast the parameter to T. And check contains properly when step != 1. --- src/library/scala/Range.scala | 25 +++++++++++++++++++------ src/library/scala/util/control/Exception.scala | 2 +- 2 files changed, 20 insertions(+), 7 deletions(-) diff --git a/src/library/scala/Range.scala b/src/library/scala/Range.scala index 4f21bc36dc..4cf8bac950 100644 --- a/src/library/scala/Range.scala +++ b/src/library/scala/Range.scala @@ -12,6 +12,7 @@ package scala import collection.immutable.Vector import collection.generic.VectorView +import util.control.Exception.catching /**

* GenericRange is a generified version of the @@ -90,14 +91,26 @@ extends VectorView[T, Vector[T]] with RangeToString[T] { start + idx * step } + // The contains situation makes for some interesting code. + // This attempts to check containerhood in a range-sensible way, but + // falls back on super.contains if the cast ends up failing. override def contains(_x: Any): Boolean = { - // XXX - can we avoid this cast and still have a contains method? - val x = - try { _x.asInstanceOf[T] } - catch { case _: ClassCastException => return false } + def doContains = { + // checking for Int is important so for instance BigIntRange from + // 1 to Googlefinity can see if 5 is in there without calling super. + val x = _x match { + case i: Int => fromInt(i) + case _ => _x.asInstanceOf[T] + } + def matchesStep = (x - start) % step == zero + def withinRange = + if (step > zero) start <= x && x < trueEnd + else start >= x && x > trueEnd + + withinRange && matchesStep + } - if (step > zero) start <= x && x < trueEnd - else start >= x && x > trueEnd + catching(classOf[ClassCastException]) opt doContains getOrElse super.contains(_x) } } diff --git a/src/library/scala/util/control/Exception.scala b/src/library/scala/util/control/Exception.scala index 49dad8cf9f..769be2fef8 100644 --- a/src/library/scala/util/control/Exception.scala +++ b/src/library/scala/util/control/Exception.scala @@ -194,7 +194,7 @@ object Exception } /** Private **/ - private def wouldMatch(x: AnyRef, classes: collection.Sequence[Class[_]]): Boolean = + private def wouldMatch(x: Throwable, classes: collection.Sequence[Class[_]]): Boolean = classes exists (_ isAssignableFrom x.getClass) private def pfFromExceptions(exceptions: Class[_]*) = -- cgit v1.2.3