What's the difference between A<:B and +B in Scala?

后端 未结 4 1454
挽巷
挽巷 2021-01-29 18:20

What\'s the difference between

[A <: B]

and

[+B]

in Scala?

4条回答
  •  时光说笑
    2021-01-29 18:58

    Q[A <: B] means that class Q can take any class A that is a subclass of B.

    Q[+B] means that Q can take any class, but if A is a subclass of B, then Q[A] is considered to be a subclass of Q[B].

    Q[+A <: B] means that class Q can only take subclasses of B as 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 an Output class with a toFile method, you could use that method in any class that could be passed into Q.

    The second is useful when you want to make collections that behave the same way as the original classes. If you take B and you make a subclass A, then you can pass A in anywhere where B is expected. But if you take a collection of B, Q[B], is it true that you can always pass in Q[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; Q covaries--follows along with--B's subclasses' inheritance relationship).

提交回复
热议问题