简体   繁体   English

从类实例访问伴随对象的属性

[英]accessing properties of companion object from class instance

What I would like to do is create an instance of a class which has a companion object, and be able to access the static fields in the companion object from the instance of the class. 我想做的是创建一个具有伴随对象的类的实例,并能够从该类的实例访问伴随对象中的静态字段。

class Person(name: String, age: Integer)
{
    def getAge(): Integer = { age }
    def getName(): String = { name }
}

object Person
{
    def create(name: String, age: Integer)
    {
        new Person(name, age)
    }

    val species = "homoSapiens"
}

object mainMethod
{
    def main(args: Array[String]): Unit =
    {
        // this is what I want to make work
        val person = Person.create("Sarah", 18)
        println(person.species)
    }
}

I understand that with the current setup the species property will not be found when referencing the class instance. 我知道,在当前设置下,引用类实例时将不会找到种类属性。 My question is, is it possible to manipulate the code above in some way in order to make this work? 我的问题是,是否可以通过某种方式操纵上面的代码以使其工作?

This is how you can do that: 这样可以做到这一点:

class Person(name: String, age: Int) {
  def getAge: Integer = {
    age
  }

  def getName: String = {
    name
  }

  def species: String = Person.species
}

object Person {
  def apply(name: String, age: Int): Person = new Person(name, age)

  def species = "homoSapiens"
}

object Solution extends App {
  val person = Person("sarah", 18)

  println(person.species)
}

If you really wanna have it via property, there is one of the weird way: 如果您真的想通过财产拥有它,那么有一种奇怪的方法:

class Person(name: String, age: Integer) {
  def getAge(): Integer = { age }
  def getName(): String = { name }
}

trait PersonProps {
  val species = "homoSapiens"
}

object Person {
  def create(name: String, age: Integer) = {
    new Person(name, age) with PersonProps
  }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM