Type expression does not match expected type B

I have the following code to understand the covariant and lower bounds, I intentionally force the code to compile errors.

It works getOrElse, which is similar to the getOrElse[+ T] option method .

I would ask why getOrElse2they getOrElse3do not work in order to better understand the covariant and lower bounds.

A compilation error is inserted as comments in the code:

class  MyOption[+A](val x: A) {
  def get():A = x

  //similar to Option.getOrElse,which works
  def getOrElse[B>:A ](default: => B): B = {
    if (x != null) x else  default
  }

  //Compiling Error: Expression of type A doesn't conform to Expected type B
  def getOrElse2[B, A<:B ](default: => B): B = {
    if (x != null) x else  default
  }

  //Covariant type A occurs in controvariant position in type A of value B
  def getOrElse3[B <: A](default:=>B): A = {
    if (x != null) x else  default
  }
}
+4
source share
2 answers

1. getOrElse3[B <: A]: B controvariant A, B / A, A, A. :

//Error:covariant type A occurs in contravariant position in type A of value default
def getOrElse3(default: A): A = {
  if (x != null) x else default
}

Option? A to A, Some(1) , : Option[AnyVal].

2. def getOrElse2[B, A<:B ]: A<:B A B ( A). x generic type A B, .

+1

[A <: B] getOrElse2, A, A, x, @chengpohi.

getOrElse3, [B <: A] trait Function1, , :

trait Function1[-T1, +R] extends AnyRef {
  abstract def apply(v1: T1): R
  // ...
}

[+ A] S of A MyOption [S] (x: S) MyOption [A] (x: A); getOrElse3 [S] getOrElse3 [A] - Function1. :

// Compiling Error: covariant type A occurs in contravariant position in type A of value default
def printDefault(default: A): Unit = {
  println(default)
}

[+ A], A, , getOrElse, Function1.

+1

Source: https://habr.com/ru/post/1682558/


All Articles