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

scala – 为什么不能将this.type用于新的实例

发布时间:2020-12-16 09:11:25 所属栏目:安全 来源:网络整理
导读:我想使用this.type来定义一个使不可变的case类的新实例的方法.这样的事情 trait Expression{ def left : Expression def right : Expression def new_with_changes(l : Expression,r : Expression) : this.type}case class Derived(left : Expression,right
我想使用this.type来定义一个使不可变的case类的新实例的方法.这样的事情

trait Expression
{
  def left : Expression
  def right : Expression

  def new_with_changes(l : Expression,r : Expression) : this.type
}

case class Derived(left : Expression,right : Expression)
{
  def new_with_changes(l : Expression,r : Expression) : this.type =
  {
    new Derived(left,right)
  }
}

不幸的是,编译器抱怨

test.scala:13: error: type mismatch;
 found   : Derived
 required: Derived.this.type
    new Derived(left,right)
    ^
one error found

新的case类怎么不匹配this.type?

如果我将this.type更改为Base在Base.new_with_changes中,Derived.new_with_changes中的Derived.new_with_changes可以使用,但它似乎错过了this.type的优点.

编辑:这个问题的真正意图是为什么在Scala中没有一个等同的方式声明down的调用者执行downcast,这与this.type一样,但是对于一般类型.我不认为这会很容易,但会很好.

解决方法

[注意:我不建议你这样做.]有一个公平的机会,你可以完成你想要的.对this.type的转换是一种谎言,但JVM不知道并且不能抛出异常,因为单例类型是scala概念.

现在,如果你真的使用this.type的单例属性,这样会让你很麻烦.但是,如果你想做的就是获得协变回报类型,而不用输入任何麻烦,只有巨大的丑陋演员的小缺点在整个地方:

trait Expression
{
  def left : Expression
  def right : Expression

  def new_with_changes(l : Expression,r : Expression) : this.type
}

case class Derived1(left : Expression,right : Expression) extends Expression {
  def new_with_changes(l : Expression,r : Expression) =
    Derived1(left,right).asInstanceOf[this.type]

  def foo() = "Derived1"
}

case class Derived2(left : Expression,r : Expression) =
    Derived2(left,right).asInstanceOf[this.type]

  def bar() = "Derived2"  
}

在行动中:

scala> Derived1(Derived1(null,null),null)
res0: Derived1 = Derived1(Derived1(null,null)

scala> res0.new_with_changes(res0,null).bar
<console>:6: error: value bar is not a member of Derived1
       res0.new_with_changes(res0,null).bar
                                         ^

scala> res0.new_with_changes(res0,null).foo
res2: java.lang.String = Derived1

scala> Derived2(Derived2(null,null)
res3: Derived2 = Derived2(Derived2(null,null)

scala> res3.new_with_changes(null,res3).foo
<console>:6: error: value foo is not a member of Derived2
       res3.new_with_changes(null,res3).foo
                                         ^

scala> res3.new_with_changes(null,res3).bar
res6: java.lang.String = Derived2

(编辑:李大同)

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

    推荐文章
      热点阅读