Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Val cannot be reassigned error in constructor

I want to reassign a new value in the constructor, but I can’t.

class InstantDate {

    private var date: LocalDateTime? = null

        constructor(date: String) {
        if (date.contains(" ")) 
        {
            date = date.replace(" ", "T")
            this.date = LocalDateTime.parse(date)
        }
    
    }

}

I get the error "val cannot be reassigned."

How can I solve this without creating a new value? Thank you.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

Methods and constructor parameters are implicitly vals in Kotlin and cannot be re-assigned. Either create local var, or maybe inline your replace operation on string like so:

class InstantDate {
    private var date: LocalDateTime? = null
    
    constructor(date: String) {
        if (date.contains(" ")) {
            this.date = LocalDateTime.parse(date.replace(" ", "T"))
        }
    }
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading