Home > Software engineering >  Returning one of multiple class types from a data class
Returning one of multiple class types from a data class

Time:10-11

I have scenario where in I have a "Lookup Table" class that holds getters and setters for multiple class types. As I'm interfacing with a database, I need to provide a way to provide a result boolean and then the class instance which was requested.

For example. Say I have an AssetStatus, StockItemStatus and NominalCode class. I would have to write the following data class for each:

data class LookupResult(
    val wasSuccessful: Boolean = false, 
    val resultClass: AssetStatus? = null, 
)

// or

data class LookupResult(
    val wasSuccessful: Boolean = false, 
    val resultClass: StockItemStatus? = null, 
)

// or

data class LookupResult(
    val wasSuccessful: Boolean = false, 
    val resultClass: NominalCode? = null, 
)

Ideally I don't want to have to repeat myself so I was wondering if I could write one data class (or normal class?) which is able to return one of my multiple Lookup classes?

Initially I thought it would have needed to be Any but after looking into this, that might not be the best case for what I want.

So is there a way of sticking to writing once but not repeating? Or is it something I have to do?

Edit:-

All of my class types would have the following structure (note: I'm using Spring Boot as back end) :

@Entity
@Table(name = "lookup_asset_status")
data class AssetStatus(
    @Id
    @GeneratedValue(strategy = IDENTITY)
    @Column(name = "asset_status_id")
    val id: Long? = null, 

    @Column(name = "asset_status_name")
    val name: String = "", 
)

... 
// Repeat for each entity type
... 

CodePudding user response:

If I understand correctly, you want something like this:

data class LookupResult<T>(
    val wasSuccessful: Boolean = false,
    val resultClass: T? = null,
)

Each of the classes would be written as LookupResult<AssetStatus>, LookupResult<StockItemStatus> and LookupResult<NominalCode>.

If your method needs to be able to return any of those three classes, then it should be declared to return LookupResult<*>. Note that you can only access the members of Any when you access the resultClass of a LookupResult<*>, because you don't know which exact look up result it is.

  • Related