Search code examples
scalainheritanceextendscase-class

Get only super class fields


case class Person(name: String, 
                  override val age: Int, 
                  override val address: String
    ) extends Details(age, address)

class Details(val age: Int, val address: String)

val person = Person("Alex", 33, "Europe")

val details = person.asInstanceOf[Details] // ??? 
println(details) // I want only Details class fields

I have these 2 classes. In reality, both have a lot of fields. Somewhere, I need only field of superclass, taken from Person class.

There is a nice way to get only super class values and not mapping them field by field?

*I'm pretty sure I'll have some problems with json writes for class Details (which is not a case class and have not a singleton object, but this is another subject)


Solution

  • If I get your question correctly, then you might be asking me runtime polymorphism or dynamic method dispatch from java. If so, you may have to create both the class and not case class

    class Details( val age: Int,  val address: String)
    
     class Person(name: String,
                      override val age: Int,
                      override val  address: String
                     ) extends Details(age, address) {
    
    }
    

    Now create the object of person and reference to superclass (Details)

    val detail:Details =  new Person("Alex", 33, "Europe")
    
    
    println(detail.address)
    println(detail.age)
    

    This way you will be able to get the only address and age

    Another way is like , why can't we create the Details a separate entity like:

    case class Details(  age: Int,   address: String)
    
     case class Person(name: String,
                       details: Details
                     )
    
    
    val detail =   Person("Alex", Details(10,"Europe") )
    
    

    Output:

    println(detail.details)
    
    Details(10,Europe)