2

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
  • At what moment you get the smart cast exception? In the posted code I don't see the place where it might happen. Commented Jul 18, 2020 at 11:55

1 Answer 1

1

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>()
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.