+- Signs in Generic Declaration in Scala

前端 未结 3 1234
走了就别回头了
走了就别回头了 2021-01-30 20:33

I was looking at the documentation for PartialFunction in this link:

trait PartialFunction[-A, +B] extends (A) ⇒ B

Maybe someone can help clari

3条回答
  •  迷失自我
    2021-01-30 21:00

    It's covariance and contravariance. https://en.wikipedia.org/wiki/Covariance_and_contravariance_(computer_science)

    Basically it says for Generic types how inheritance will work. Easy sample from Scala is - trait Seq[+A] Because of the + , the code

    val s: Seq[Person] = Seq[Student]()
    

    will compile because Student extends Person. Without the + it won't work

    A bit more complex sample -

    class C[-A, +B] {
      def foo(param: A): B = ???
    }
    
    class Person(val name: String)
    
    class Student(name: String, val university: String) extends Person(name)
    
    val sample: C[Student, Person] = new C[Person, Student]
    

提交回复
热议问题