Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
221 views
in Technique[技术] by (71.8m points)

scala - Understanding risks of @uncheckedVariance in method argument

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 ?

    }

}
question from:https://stackoverflow.com/questions/65933396/understanding-risks-of-uncheckedvariance-in-method-argument

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)
Waitting for answers

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...