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
CodePudding user response:
Your various calendar.set
calls need to be inside an init
block:
class savedData(hour: Int, minutes: Int) {
var calendar = Calendar.getInstance()
init {
calendar.set(Calendar.HOUR_OF_DAY, hour)
calendar.set(Calendar.MINUTE, minutes)
calendar.set(Calendar.SECOND, 0)
}
}
Class-level statements can only be property declarations, not code to initialize them.
Another approach would be to use a scoping function like apply
:
class savedData(hour: Int, minutes: Int) {
var calendar = Calendar.getInstance().apply {
set(Calendar.HOUR_OF_DAY, hour)
set(Calendar.MINUTE, minutes)
set(Calendar.SECOND, 0)
}
}
CodePudding user response:
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.
CodePudding user response:
The other 2 answers are basically correct. However, you might also be interested in initializing the property the lazy
way, so that it won't be initialized as long as nothing needs it:
class savedData(hour:Int, Minutes:Int) {
var calendar: Calendar by lazy {
Calendar.getInstance().apply {
set(Calendar.HOUR_OF_DAY, hour)
set(Calendar.MINUTE, Minutes)
set(Calendar.SECOND, 0)
}
}
}
This is specially useful for creating an instance of a class with resource-intensive init process.