consoleau / kassava

This library provides some useful kotlin extension functions for implementing toString(), hashCode() and equals() without all of the boilerplate.
Apache License 2.0
115 stars 13 forks source link

Use callable instead of property? #4

Open thauk-copperleaf opened 6 years ago

thauk-copperleaf commented 6 years ago

Instead of providing a list of properties, can I refer to a member of the class that's a callable function, which will return a the value to use for comparisons?

jamesbassett commented 6 years ago

Interesting...what use cases did you have in mind? Instance functions, extension functions?

By using callable you lose the ability to enforce that the callable's are actually compatible with the object's being compared (there's no receiver in the type signature like with KProperty), so you run the risk of getting IllegalArgumentException: object is not an instance of declaring class.

thauk-copperleaf commented 6 years ago

I have a bunch of POKOs that have Hibernate annotations, and matching "mixin" classes that are used to serialize the POKOs with Jackson. An oversimplified example might look like this:

@Entity
class Foo {
    @Id
    @GeneratedValue(generator = "UUID")
    @GenericGenerator(
            name = "UUID",
            strategy = "org.hibernate.id.UUIDGenerator"
    )
    @Column(name = "id", updatable = false, nullable = false)
    @JsonIgnore
    var id: UUID? = null

    @Column(name = "name")
    var name: String? = null

    fun getTransformedName(): String? {
        return name?.capitalize()
    }
}

@JsonPropertyOrder("name", "transformedName")
class FooMixin {
    @JsonProperty("transformedName", access = JsonProperty.Access.READ_ONLY)
    abstract fun getTransformedName(): String?
}

Let's say I need to compare two Foo entities for functional equality. That means I want to skip the id field, but I want to compare the name field, and also what is essentially a transformed name field.