Understanding risks of @uncheckedVariance in method argument

64 views Asked by At

I don't success to figure out how following example can be risky.

To be more specific to my case, the exFrom method is protected and called by other methods giving to it exactly an object of type X. In that situation i don't figure out how it can be dangerous but i'm not confident enough about it.


trait A { val a: Int }

case class B(val a: Int) extends A

case class C(val a: Int) extends A

case class Toto[+X <: A](val x: X) {

    def exFrom(in: X @uncheckedVariance): Toto[X] = Toto(in)

    protected def protectedFrom(in: X @uncheckedVariance): Toto[X] = Toto(in)

    // Is using protectedFrom in situation like in f is risky ? 
    def f: Toto[X] = protectedFrom(ops(x): X)

}

object TestToto {

    def main(args: Array[String]): Unit = {
        val t: Toto[B] = Toto(B(1))
        val ta: Toto[A] = t // Works thanks to covariance on X

        ta.exFrom(B(2)) // Works
        ta.exFrom(C(2)) // Works

        // Do you have example of how it can failed ?

    }

}
0

There are 0 answers