[B >: A] 在 Scala 中做什么? [英] What does [B >: A] do in Scala?

查看:37
本文介绍了[B >: A] 在 Scala 中做什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

[B >: A] 在 Scala 中是什么意思?有什么影响?

What does [B >: A] mean in Scala? And what are the effects?

示例参考:http://www.scala-lang.org/node/129

class Stack[+A] {
    def push[B >: A](elem: B): Stack[B] = new Stack[B] {
        override def top: B = elem
        override def pop: Stack[B] = Stack.this
        override def toString() = elem.toString() + " " + Stack.this.toString()
    }
    def top: A = error("no element on stack")
    def pop: Stack[A] = error("no element on stack")
    override def toString() = ""
}

object VariancesTest extends Application {
    var s: Stack[Any] = new Stack().push("hello");
    s = s.push(new Object())
    s = s.push(7)
    println(s)
}

推荐答案

[B >: A] 是一个下限类型.这意味着 B 被限制为 A 的超类型.

[B >: A] is a lower type bound. It means that B is constrained to be a supertype of A.

类似地,[B <: A] 是类型上限,这意味着 B 被约束为 A 的子类型.

Similarly [B <: A] is an upper type bound, meaning that B is constrained to be a subtype of A.

在您展示的示例中,您可以将 B 类型的元素推送到包含 A 元素的堆栈上,但结果是B 元素.

In the example you've shown, you're allowed to push an element of type B onto a stack containing A elements, but the result is a stack of B elements.

你看到这个的页面实际上有一个链接到另一个关于下限类型,其中包括显示效果的示例.

The page where you saw this actually has a link to another page about lower type bounds, which includes an example showing the effect.

这篇关于[B &gt;: A] 在 Scala 中做什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆