diff options
author | Adriaan Moors <adriaan.moors@epfl.ch> | 2012-06-04 15:35:35 +0200 |
---|---|---|
committer | Eugene Burmako <xeno.by@gmail.com> | 2012-06-08 15:35:09 +0200 |
commit | 6b3ef4f1676adcbe6dbdbf59a3bd359f339b0626 (patch) | |
tree | 44de8ceb19ff698d92c17bc37fcd6bbb84731ba1 /src/library/scala | |
parent | 10292e4acbb8eb0143a5a087c750ed9699f31807 (diff) | |
download | scala-6b3ef4f1676adcbe6dbdbf59a3bd359f339b0626.tar.gz scala-6b3ef4f1676adcbe6dbdbf59a3bd359f339b0626.tar.bz2 scala-6b3ef4f1676adcbe6dbdbf59a3bd359f339b0626.zip |
turn unchecked type patterns into checked ones
the pattern `(_: T)` is made checkable using (ct: ClassTag[T]).unapply
by rewriting it to `ct(_: T)` (if there's a ClassTag[T] available)
similarly for extractors: if the formal type of the unapply method
is an uncheckable type, wrap in the corresponding classtag extractor (if available)
don't trigger rewrite on non-toplevel unchecked types
(i.e., only look at type constructor part of T when looking for unchecked types)
TODO: find outer match to figure out if we're supposed to be unchecked
would like to give users a chance to opt-out from the wrapping,
but finding the match to which this pattern belongs turned out to be tricky...
Diffstat (limited to 'src/library/scala')
-rw-r--r-- | src/library/scala/reflect/ClassTag.scala | 10 |
1 files changed, 10 insertions, 0 deletions
diff --git a/src/library/scala/reflect/ClassTag.scala b/src/library/scala/reflect/ClassTag.scala index 350003a8d8..f753dfbcbb 100644 --- a/src/library/scala/reflect/ClassTag.scala +++ b/src/library/scala/reflect/ClassTag.scala @@ -44,6 +44,16 @@ trait ClassTag[T] extends Equals with Serializable { case _ => java.lang.reflect.Array.newInstance(runtimeClass, len).asInstanceOf[Array[T]] } + /** A ClassTag[T] can serve as an extractor that matches only objects of type T. + * + * The compiler tries to turn unchecked type tests in pattern matches into checked ones + * by wrapping a `(_: T)` type pattern as `ct(_: T)`, where `ct` is the `ClassTag[T]` instance. + * Type tests necessary before calling other extractors are treated similarly. + * `SomeExtractor(...)` is turned into `ct(SomeExtractor(...))` if `T` in `SomeExtractor.unapply(x: T)` + * is uncheckable, but we have an instance of `ClassTag[T]`. + */ + def unapply(x: Any): Option[T] = if (runtimeClass.isAssignableFrom(x.getClass)) Some(x.asInstanceOf[T]) else None + /** case class accessories */ override def canEqual(x: Any) = x.isInstanceOf[ClassTag[_]] override def equals(x: Any) = x.isInstanceOf[ClassTag[_]] && this.runtimeClass == x.asInstanceOf[ClassTag[_]].runtimeClass |