Initiation of val in data class



  • I have a class that takes one variable and treats it a little for further storage. I'd like to have a variable. value int all functions data class (whispers) equals and hashCode should only be new. value)

    data class GF(var value: Int = 0) {
    
    init {
        value = value % 10
    }
    

    }

    I tried to do this:

    data class GF {
    val value: Int

    constructor(data: Int = 0) {
        value = data % 10
    }
    

    }

    However, I get: Data class must have at least one primary constructor parameter



  • Make a field in the designer private and add another field. value In your class:

    data class GF(private var data: Int) {
        val value: Int
    
    init {
        data %= 10
        value = data
    }
    

    }

    Thus, equals and hashCode will use the updated value. C copy There's no problem either.


Log in to reply
 

Suggested Topics

  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2