bmoody
bmoody

Reputation: 143

Validate at least 1 of a set of args is present in Kotlin class constructor

Scenario

I need to create a Kotlin class that can receive up to 4 arguments for its constructor, but only requires at least 1 out of a set of 3 (the fourth being entirely optional). To illustrate:

class Pie {

// Completely optional, the constructor should use it if present, otherwise it may be null.
    var topping: String?   

// Of these three [fillingA, fillingB, fillingC] 1 or more must be present.
    var fillingA: String?   
    var fillingB: String?  
    var fillingC: String?
}

Thoughts

I've attempted to use Kotlin init{} blocks for validation, or telescoping constructors, but it gets ugly fast and I've yet to solve the issue. I have not found anything in the kotlinlang.org docs on primary/secondary constructors that is more elegant, though. My preference would be to find something similar to the @Size or @NotNull annotations, but I have failed to locate anything close.

It is important to note that I am using this class as a model for an API response.

Question

What is the most concise way to validate that a Kotlin class has at least 1 of a set of arguments passed to its constructor?

Upvotes: 0

Views: 251

Answers (1)

Luciano Ferruzzi
Luciano Ferruzzi

Reputation: 1112

Are this fillings interchangeable? You could assume that fillingA is always required and the other ones are optional, something like this:

class Pie constructor(
    val fillingA: String,
    val fillingB: String? = null,
    val fillingC: String? = null,
    val topping: String? = null
){...}

Upvotes: 1

Related Questions