Construct an arraylist inside model

Viewed 75

I have a model class

    @Entity
    @Table(name = "registration_requests")
    class RegistrationRequest(
    @Column(unique = true)
    @Size(min = 2)
    var username: String = "",
    @Size(min = 10, max = 60)
    var password: String = "",
    @Size(min = 9, max = 9)
    var evaluations: String = "",  
    @Transient
    var question: String = "",      
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    var id: Long = 0,
    @DateTimeFormat
    val createdAt: Date = Date.from(Instant.now())
    ) {
        @Transient
        lateinit var evaluationImages: Collection<EvaluationImage>
    }

Now I want to initialize the field evaluationImages in a Service

var retVal = RegistrationRequest(userDetails.username, userDetails.password, "", "")
retVal.evaluationImages = ArrayList<EvaluationImage>()

I am receiving the error "Smart cast to 'kotlin.collections.ArrayList /* = java.util.ArrayList */' is impossible, because 'retVal.evaluationImages' is a complex expression".

My goal further is to add objects of class EvaluationImage to retVal.evaluationImages. Can anyone please help ?

1 Answers

I suppose you want evaluationImages to look like a mutable list in some scope but as an immutable collection from the outside of the scope. Then, you may do the following

class RegistrationRequest(...) {
    internal val _evaluationImages = mutableListOf<String>()
    val evaluationImages: Collection<String> get() = _evaluationImages
}

The internal modifier allows access to the property from inside the same Gradle project but disallows it from the outside.

Another option is to have two different "views" on your class:

interface A {
    val images: MutableList<String>
}

interface B {
    val images: Collection<String>
}

class C : A, B {
    override val images = mutableListOf<String>()
}
Related