scala – 通过一组构造函数传递参数的问题
发布时间:2020-12-16 09:52:31 所属栏目:安全 来源:网络整理
导读:我的问题是 scala继承细节.我有以下代码. package scalasandboxobject Main { def main(args: Array[String]): Unit = { val creature: Creature = new Human("First") creature.rename("Second") creature.introduce }}class Creature(var name: String) {
我的问题是
scala继承细节.我有以下代码.
package scalasandbox object Main { def main(args: Array[String]): Unit = { val creature: Creature = new Human("First") creature.rename("Second") creature.introduce } } class Creature(var name: String) { def introduce = println("I'm creature: " + name) def rename(newName: String) = { println("Creature was renamed to: " + newName) name = newName } } class Human(name: String) extends Creature(name) { override def introduce = println("I'm Human: " + name) } 产生以下输出 Creature was renamed to: Second I'm human: First 我希望它是“我是人类:第二”,因为重命名方法应该改变字段值.我用反编译器打开了Human类: package scalasandbox; import scala.Predef.; import scala.ScalaObject; import scala.collection.mutable.StringBuilder; import scala.reflect.ScalaSignature; @ScalaSignature(bytes=" 06 01 212A! 01 02 01 13t) 01*^7b]*t1! 01 07tG 06d 27m]1oIn| 07p 01 01 24 07 011! 02 05 02b 215t!! 03 02n 05tA1I]3biV 24Xr 05 02f 355tABC 01 16 03 25 318- 317b 23tyABA 06TG 06d 27m 242kK 16$b 02Ct 01 05 03 05 13 21 02n 02t9fW. 32t 03'Yq!a 03 13n 05Ua 21A 02)sK 22,g- 03 02 301t11 13 36:j] 36T!! 06 07t 13i 01A 21A 16 02rqJg. 33;?)taR 04 05 02b 01!) 21# 07a 01%!)q 04 01C!A 05I 21N 34;s_ 22,8-Z 13 02CA 211BI 05 03G1 21A! 268ji 02") public class Human extends Creature implements ScalaObject { private final String name; public void introduce() { Predef..MODULE$.println(new StringBuilder().append("I'm Human: ").append(this.name).toString()); } public Human(String name) { super(name); } } 并看到“私有最终字符串名称;”那里.我认为它隐藏了生物名称字段.和 Predef..MODULE$.println(new StringBuilder().append("I'm Human: ").append(this.name).toString()); 由于“this.name”而不是方法调用“this.name()”,这些东西看起来也很可疑.任何人都可以解释我的错误在哪里以及实现这两个类的正确方法是什么? 解决方法
您在Human类中使用的name变量解析为Human的构造函数参数,Scala将自动为构造函数外部使用的构造函数参数创建私有val.在你的情况下这是不幸的.你可以阻止这个,例如通过在Human中以不同方式命名您的参数,例如纳米:
class Human(nm: String) extends Creature(nm) (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |