本文介绍了为什么函数[-A1,...,+ B]不允许任何超类型作为参数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我认为可以将协变(至少对于对象)定义为'使用更窄(子)类型的值代替更宽(超)类型'的值的能力,并且该逆变是与此相反。

显然,Scala函数是函数[-A1,...,+ B]用于逆变参数类型A1等和协变返回类型的实例。这对分类函数很方便,上面的定义是不是意味着我可以传递任何超类型的参数?



请告知我错在哪里。

解决方案

协变和逆变是 质量参数的品质。 (它们是取决于参数的品质,但它们会对类进行声明。)

因此, Function1 [-A,+ B] 意味着 c> A 的超类可以被视为原始函数的子类 / b>

让我们在实践中看到这一点:

  class A 
类B延伸A
val printB:B =>单位= {b => println(Blah blah)}
val printA:A =>单位= {a => println(Blah blah blah)}

现在假设你需要一个知道如何打印 B :

  def needsB(f:B => Unit,你可以传入 printB   

/ code>。但你也可以 传入 printA ,因为它也知道如何打印 B s> (以及更多!),就好像 A =>单元是 B =>的子类。单元。这正是反转意味着什么。这并不意味着您可以将 Option [Double] 传递给 printB ,并获得除编译时错误以外的任何内容!
(协方差是另一种情况: M [B] if B<:A 。)


I believe one can define covariance (at least, for objects) as 'the ability to use a value of a narrower (sub) type in place of a value of some wider (super) type', and that contravariance is the exact opposite of this.

Apparently, Scala functions are instances of Function[-A1,...,+B] for contravariant parameter types A1, etc. and covariant return type, B. While this is handy for subtyping on Functions, shouldn't the above definition mean I can pass any supertypes as parameters?

Please advise where I'm mistaken.

解决方案

Covariance and contravariance are qualities of the class not qualities of the parameters. (They are qualities that depend on the parameters, but they make statements about the class.)

So, Function1[-A,+B] means that a function that takes superclasses of A can be viewed as a subclass of the original function.

Let's see this in practice:

class A
class B extends A
val printB: B => Unit = { b => println("Blah blah") }
val printA: A => Unit = { a => println("Blah blah blah") }

Now suppose you require a function that knows how to print a B:

def needsB(f: B => Unit, b: B) = f(b)

You could pass in printB. But you could also pass in printA, since it also knows how to print Bs (and more!), just as if A => Unit was a subclass of B => Unit. This is exactly what contravariance means. It doesn't mean you can pass Option[Double] into printB and get anything but a compile-time error!

(Covariance is the other case: M[B] <: M[A] if B <: A.)

这篇关于为什么函数[-A1,...,+ B]不允许任何超类型作为参数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-31 19:39