What’s the difference between
[A <: B]
and
[+B]
in Scala?
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
Q[A <: B]means that classQcan take any classAthat is a subclass ofB.Q[+B]means thatQcan take any class, but ifAis a subclass ofB, thenQ[A]is considered to be a subclass ofQ[B].Q[+A <: B]means that classQcan only take subclasses ofBas well as propagating the subclass relationship.The first is useful when you want to do something generic, but you need to rely upon a certain set of methods in
B. For example, if you have anOutputclass with atoFilemethod, you could use that method in any class that could be passed intoQ.The second is useful when you want to make collections that behave the same way as the original classes. If you take
Band you make a subclassA, then you can passAin anywhere whereBis expected. But if you take a collection ofB,Q[B], is it true that you can always pass inQ[A]instead? In general, no; there are cases when this would be the wrong thing to do. But you can say that this is the right thing to do by using+B(covariance;Qcovaries–follows along with–B‘s subclasses’ inheritance relationship).