Skip to content

Commit 8df1d7d

Browse files
committed
1 parent 916b754 commit 8df1d7d

File tree

2 files changed

+46
-0
lines changed

2 files changed

+46
-0
lines changed
Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
1+
import scala.reflect.ClassTag
2+
3+
object IsInstanceOfClassTag {
4+
def safeCast[T: ClassTag](x: Any): Option[T] = {
5+
x match {
6+
case x: T => Some(x) // TODO error: deprecation waring
7+
case _ => None
8+
}
9+
}
10+
11+
def main(args: Array[String]): Unit = {
12+
safeCast[List[String]](List[Int](1)) match {
13+
case None =>
14+
case Some(xs) =>
15+
xs.head.substring(0)
16+
}
17+
18+
safeCast[List[_]](List[Int](1)) match {
19+
case None =>
20+
case Some(xs) =>
21+
xs.head.substring(0) // error
22+
}
23+
}
24+
}
Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,22 @@
1+
import scala.tasty.TypeTest
2+
3+
object IsInstanceOfClassTag {
4+
def safeCast[T](x: Any)(given TypeTest[Any, T]): Option[T] = {
5+
x match {
6+
case x: T => Some(x)
7+
case _ => None
8+
}
9+
}
10+
11+
def main(args: Array[String]): Unit = {
12+
safeCast[List[String]](List[Int](1)) match { // error
13+
case None =>
14+
case Some(xs) =>
15+
}
16+
17+
safeCast[List[_]](List[Int](1)) match { // error
18+
case None =>
19+
case Some(xs) =>
20+
}
21+
}
22+
}

0 commit comments

Comments
 (0)