加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > 安全 > 正文

scala – 为什么操作符的变化?

发布时间:2020-12-16 10:06:43 所属栏目:安全 来源:网络整理
导读:长时间潜伏,第一次海报. 在Scala中,我正在寻找优势,以便根据类型改变运算符.例如,为什么这样: Vector(1,2,3) :+ 4 决心成为优势: Vector(1,3) + 4 要么: 4 +: Vector(1,3) 过度: Vector(4) + Vector(1,3) 要么: Vector(1,3) ++ Vector(4,5,6) 过度: Ve
长时间潜伏,第一次海报.

在Scala中,我正在寻找优势,以便根据类型改变运算符.例如,为什么这样:

Vector(1,2,3) :+ 4

决心成为优势:

Vector(1,3) + 4

要么:

4 +: Vector(1,3)

过度:

Vector(4) + Vector(1,3)

要么:

Vector(1,3) ++ Vector(4,5,6)

过度:

Vector(1,3) + Vector(4,6)

所以,在这里我们有:,和,当它独自完成时就足够了.我是斯卡拉的新人,我会屈服.但是,对于一种试图用它的语法来清理的语言来说,这似乎是不必要的和混淆的.

我已经做了很多google和堆栈溢出搜索,并且只发现了有关特定运算符和运算符重载的问题.但是,没有背景为什么有必要将例如分成多个变体.

FWIW,我可以使用隐式类重载运算符,如下所示,但我想这只会导致经验丰富的Scala程序员使用/读取我的代码造成混淆(和tisk风险).

object AddVectorDemo {

    implicit class AddVector(vector : Vector[Any]) {
        def +(that : Vector[Any]) = vector ++ that
        def +(that : Any) = vector :+ that
    }

    def main(args : Array[String]) : Unit = {
        val u = Vector(1,3)
        val v = Vector(4,6)
        println(u + v)
        println(u + v + 7)
    }
}

输出:

Vector(1,3,4,6)
Vector(1,6,7)

解决方法

这是一个公平的问题,我认为它与遗留代码和Java兼容性有很大关系. Scala复制了Java用于字符串连接,这使事情变得复杂.

这允许我们这样做:

(new Object) + "foobar" //"java.lang.Object@5bb90b89foobar"

那么如果我们有List和我们做了List(1)“foobar”,我们应该期待什么呢?人们可能期望List(1,“foobar”)(类型为List [Any]),就像我们使用的那样得到:,但是Java启发的String-concatenation重载会使这变得复杂,因为编译器将无法解决超载.

奥德斯基甚至曾评论过:

One should never have a + method on collections that are covariant in their element type. Sets and maps are non-variant,that’s why they can have a + method. It’s all rather delicate and messy. We’d be better off if we did not try to duplicate Java’s + for String concatenation. But when Scala got designed the idea was to keep essentially all of Java’s expression syntax,including String +. And it’s too late to change that now.

关于this similar question的答案有一些讨论(尽管在不同的背景下).

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读