Scala中的重载Val [英] Overriding vals in Scala

查看:143
本文介绍了Scala中的重载Val的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图这样在Scala中覆盖val:

I have tried to override val in Scala as this:

trait T{
  val str: String
}

sealed abstract class Test extends T{
  val str: String = "str"
}

class Test1 extends Test{
  val str = super.str + "test1" //super may not be used on value str
}

但是这个拒绝编译.为什么?我想使用抽象类的值本身覆盖抽象类中的值.该怎么做?

But this refused to compile. Why? I wanted to override value in the abstract class using the abstract class's value itself. How to do this?

在我的特殊情况下,我 不能将其作为类参数传递.

In my particular case I cannot pass it as a class parameter.

推荐答案

Scala编译器不允许在val上使用super.如果您不关心重新评估,则可以使用def代替.

Scala compiler does not allow to use super on a val. If you are not caring about re-evaluation, you can just use def instead.

trait T{
  def str: String
}

sealed abstract class Test extends T{
  def str: String = "str"
}

class Test1 extends Test{
  def str = super.str + "test1" //super may not be used on value str
}

defined trait T
defined class Test
defined class Test1

这篇关于Scala中的重载Val的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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