明确函数的返回类型的自变量性质作为外部协变量容器的函数的参数 [英] Clarifying contravariance nature of the return type of a function as parameter a function of an outer convariant container
问题描述
在Option中,我们有
In Option we have
def getOrElse[B >: A](default: => B): B = this match {
case None => default
case Some(a) => a
}
def orElse[B >: A](obj: => Option[B]): Option[B] = this match {
case None => obj
case _ => this
}
在这两种情况中,我们都有:
In Either we have:
def flatMap[EE >: E, B](f: A => Either[EE, B]): Either[EE, B]
我了解发生了什么以及为什么,一个更广泛的例子可能是这样
I understand what is going and why, a rather extended example could be this
OrElse({Option [B]}).map {....}如果B等于A:>B,如果Some(a),您会得到Some(a).map(f:B => ???)然后是Kaboom
OrElse( { Option[B]}).map{....} If B is such that A :> B, then if Some(a) you get Some(a).map(f:B => ???) then Kaboom
一般来说,我认为我可以接受.我没有看到或发现的内容,因为那不是协方差和逆方差的简单示例解释为用例,我想在此进行确认:
generally speaking i think i am ok with variance. What i did not see or figure out because that is not what the simple example of co-variance and contravariance explain as use cases, and would like to confirm here:
检查函数作为参数的返回类型以检查外部容器的差异位置.
The return type of a function as parameter is checked for variance position of the outer container.
典型的例子是
Container[+A] {
def outerfunction[B](value: A): B
}
然后我们将解释A的反方差位置,这是不能做的.对于原因,我将不做完整的解释.假设我们都了解它.
We are then explained, can't do, contra-variance position for A. I will not re-do to full explanation as to why. Let's assume we all understand it.
通常不解释的是:
Container[+A] {
def outerfunction(f: ??? => A): A
}
不仅采用A类型的参数,而且采用返回A的任何函数参数.编译器也进行了大量检查.我想知道它是否停在这里,还是可以产生A的任何东西,作为Container函数的参数.
It is not just taking a parameter of type A, but also taking any function parameter that return that A. The compiler goes at length to check that too. I wonder if it stops here, or if it is anything that can produce an A, as parameter to a function of the Container.
推荐答案
您的理解是完全正确的.老实说,我不确定问题到底是什么,但是我会假设它是-编译器在以下情况下检查的地方:
Your understanding is completely correct. To be honest, I am not sure what exactly is the question, but I will assume it's - which places does compiler check in a case such as:
trait Container[+A] {
def outerfunction(f: String => A): A
}
答案是-全部.
因此,当编译器看到 trait容器[+ A]
时,它将检查该 Container
的正文中是否出现所有 A
,看看他们是否在:
So when compiler sees trait Container[+A]
, it will check the body of that Container
for all occurrences of A
, to see if they are in:
- 参数位置(带来了反要求)
- 返回类型位置(协变要求)
- 两者(不变要求)
- 都不是(所谓的幻像方差).
如果是 Container [+ A]
,它将要求所有出现的 A
处于协变位置,这意味着字符串=>一个
.
In case of Container[+A]
, it will require that all occurrences of A
are in covariant position, meaning that it will have a problem with String => A
.
就这么简单.不管它是否是内部功能",或外部功能".
It's as simple as that. Doesn't matter if it's an "inner function" or an "outer function".
这篇关于明确函数的返回类型的自变量性质作为外部协变量容器的函数的参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!