Companion object in Kotlin
Just switching from Java to Kotlin. There was a question, the answer to which, unfortunately, I could not find.
There is an abstract class with several abstract variables, which will then be subjected to dozens of tests. Testing with JUnit. The annotated @BeforeClass
and @AfterClass
methods are required to be static, and I see only one way to resolve the whitespace: push the methods inside companion object
, where you can use @JvmStatic
, but at the same time, the @BeforeClass
method calls the abstract a variable that is set by each implementation separately. Accordingly, how can I access a variable from an external class? Or maybe there is another way to solve such a problem? Code:
abstract class TemplateConfig {
abstract val template : String?
companion object {
lateinit var h: Handle
@BeforeClass
@JvmStatic
fun setUp() {
h = dbi.value.open()
//Здесь используется абстрактная переменная
//
//if (template != null) {
// h.createStatement(template).execute()
//}
}
@AfterClass
@JvmStatic
fun tearDown() {
h.close()
}
//{...Объявление и инициализация других переменных...}
}
}
1 answers
If I understand correctly, you are trying in a static method to refer to a non-static variable / method that is set in the descendant class. It won't work that way. The only solution I can see is to define the field as static and, when initializing the descendant class, set it to a value.
object Demo {
protected var value:String
@BeforeClass
fun setUp() {
println(value)
}
@AfterClass
fun destroy() {
}
}
internal class SubClass:Demo() {
companion object {
init {
Demo.value = "this is value"
}
}
}