经验首页 前端设计 程序设计 Java相关 移动开发 数据库/运维 软件/图像 大数据/云计算 其他经验
当前位置:技术经验 » Java相关 » Scala » 查看文章
Scala Type Parameters 2
来源:cnblogs  作者:afewnotes  时间:2019/10/10 8:54:56  对本文有异议
  • 类型关系

    Scala 支持在泛型类上使用型变注释,用来表示复杂类型、组合类型的子类型关系间的相关性

    • 协变 +T,变化方向相同,通常用在生产

      假设 A extends T, 对于 Clazz[+T],则 Clazz[A] 也可看做 Clazz[T]

      1. // 官网示例
      2. abstract class Animal {
      3. def name: String
      4. }
      5. case class Cat(name: String) extends Animal
      6. case class Dog(name: String) extends Animal

      由于 Scala 标准库中不可变 List 的定义为 List[+A],因此 List[Cat]List[Animal] 的子类型, List[Dog] 也是 List[Animal] 的子类型,所以可直接将他们当作 List[Animal] 使用。

      1. // 官网示例
      2. object CovarianceTest extends App {
      3. def printAnimalNames(animals: List[Animal]): Unit = {
      4. animals.foreach { animal =>
      5. println(animal.name)
      6. }
      7. }
      8. val cats: List[Cat] = List(Cat("Whiskers"), Cat("Tom"))
      9. val dogs: List[Dog] = List(Dog("Fido"), Dog("Rex"))
      10. printAnimalNames(cats)
      11. // Whiskers
      12. // Tom
      13. printAnimalNames(dogs)
      14. // Fido
      15. // Rex
      16. }
    • 逆变 -T,变化方向相反,通常用在消费

      假设 A extends T, 对于 Clazz[-T],则 Clazz[T] 也可看做 Clazz[A]

      1. // 官网示例
      2. abstract class Printer[-A] {
      3. def print(value: A): Unit
      4. }
      5. class AnimalPrinter extends Printer[Animal] {
      6. def print(animal: Animal): Unit =
      7. println("The animal's name is: " + animal.name)
      8. }
      9. class CatPrinter extends Printer[Cat] {
      10. def print(cat: Cat): Unit =
      11. println("The cat's name is: " + cat.name)
      12. }
      13. object ContravarianceTest extends App {
      14. val myCat: Cat = Cat("Boots")
      15. def printMyCat(printer: Printer[Cat]): Unit = {
      16. printer.print(myCat)
      17. }
      18. val catPrinter: Printer[Cat] = new CatPrinter
      19. val animalPrinter: Printer[Animal] = new AnimalPrinter
      20. printMyCat(catPrinter)
      21. printMyCat(animalPrinter) // 将 Printer[Animal] 当作 Printer[Cat] 使用
      22. }

原文链接:http://www.cnblogs.com/yuanzam/p/11645056.html

 友情链接:直通硅谷  点职佳  北美留学生论坛

本站QQ群:前端 618073944 | Java 606181507 | Python 626812652 | C/C++ 612253063 | 微信 634508462 | 苹果 692586424 | C#/.net 182808419 | PHP 305140648 | 运维 608723728

W3xue 的所有内容仅供测试,对任何法律问题及风险不承担任何责任。通过使用本站内容随之而来的风险与本站无关。
关于我们  |  意见建议  |  捐助我们  |  报错有奖  |  广告合作、友情链接(目前9元/月)请联系QQ:27243702 沸活量
皖ICP备17017327号-2 皖公网安备34020702000426号