Scala covariance with lower bound

后端 未结 1 1690
忘掉有多难
忘掉有多难 2021-01-22 09:52

I am looking at scala in action book and it has this code

sealed abstract class Maybe[+A] {
    def isEmpty: Boolean
    def get: A
    def getOrElse[B >: A](         


        
1条回答
  •  囚心锁ツ
    2021-01-22 10:16

    In Scala you cannot have covariant types in method parameters.

    This is because allowing covariant types in method parameters breaks type safety.

    In order to have a covariant type you must use a bounded type:

    getOrElse[B >: A](default: B): B
    

    This says find some type, B, such that it is a superclass of A and that becomes the method return type.

    In your case A is Int and you pass in a String. The only type B which is a superclass of both Int and String is Any.

    In this case B becomes Any so the method returns Any.

    0 讨论(0)
提交回复
热议问题