Search code examples
kotlininstance-variables

Expect member declaration error on declared variables in kotlin


I'm a beginner in kotlin and I'm getting errors on my variables when I tried using them. please I need help. Here is my code

package com.example.myapplication
import java.util.*
class savedData(hour:Int, Minutes:Int) {
  var calendar= Calendar.getInstance()
  calendar.set(Calendar.HOUR_OF_DAY,hour )
  calendar.set(Calendar.MINUTE,Minutes )
  calendar.set(Calendar.SECOND,0 )
}

I get errors when i use the calendar variable in my code above


Solution

  • This will work:

    class savedData(hour:Int, Minutes:Int) {
         var calendar= Calendar.getInstance().apply{
             this.set(Calendar.HOUR_OF_DAY,hour )
             this.set(Calendar.MINUTE,Minutes )
             this.set(Calendar.SECOND,0)
         }
    }
    

    Within a class body, its properties and methods are declared. The executable code must be inside these methods (or in init {} block, or in some setters/getters, or in scope functions like above), not in the body of the class.