在案例类中获取父类的属性 [英] Get the property of parent class in case classes

查看:57
本文介绍了在案例类中获取父类的属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我有一个案例类继承了这样的另一个类

If I have a case class that inherits another class like this

  class Person(name: String) {

  }

case class Male() extends Person("Jack") {
  def f = super.name // Doesn't work 

}

如何从Male类中获取name属性?

How to get the name property from Male class ?

推荐答案

class Person(name: String) {

在此声明中, name 不是类的字段,它只是构造函数参数.因此,可以在构造函数内部访问它,但不能在外部(包括子类中)访问它.您可以通过将其设置为 val :

In this declaration, name is not a field of the class, it is just a constructor parameter. So it is accessible inside the constructor, but not outside (including in a subclass). You can make it a field by making it a val:

class Person(val name: String) {

令人困惑的是,即使没有 val

Confusingly, constructor parameters for a case class are also fields even without val

这篇关于在案例类中获取父类的属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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