blob: 5875a38adf2444511b1d73087a3c1ceeddc9697d (
plain) (
blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
|
import scala.reflect.ClassTag
import scala.util._
object Main {
class A
def constructAs[TTT <: A](implicit ev: ClassTag[TTT]): Try[TTT] = Try {
new A()
}.flatMap {
case ev(inst) =>
val b: TTT = inst
Success(inst)
case inst: TTT =>
Success(inst)
case _ =>
val tag = implicitly[ClassTag[TTT]]
Failure(new ClassCastException(s"Failed to construct instance of class ${tag.runtimeClass.getName}"))
}
}
|