mleister
mleister

Reputation: 2565

Only get interface fields of kotlin-object

I want to reduce an object down to its basic fields (comming from an interface):

override fun findBasicById(deliveryAddressId: Long): BasicDeliveryAddress? {
    val basicDeliveryAddress = findById(deliveryAddressId) as BasicDeliveryAddress? // returns a DeliveryAddress object
    return basicDeliveryAddress // Here I still get the full DeliveryAddress!
}

However, basicDeliveryAddress still contains all fields from the class which implements the interface. How can I get rid of all fields, not declared in the interface (in this case the users-object)?

interface BasicDeliveryAddress {
    var street: String
    // some other fields
}
data class DeliveryAddress (
        override var name: String,
        // override all other fields
) : BasicDeliveryAddress {
    var user: User? = null
}

Upvotes: 1

Views: 126

Answers (1)

Tenfour04
Tenfour04

Reputation: 93649

I don't know anything about SpringBoot, so I don't know if this resolves the root problem, but you can use an anonymous implementation that wraps it as a delegate to obscure the extra fields.

fun BasicDeliveryAddress.toBasic() = object: BasicDeliveryAddress by this {}

Upvotes: 4

Related Questions