Search code examples
javajunitkotlinguicerx-kotlin

Inject constructor and companion object


I'm kind of new to Kotlin and I'm trying to Inject a value (in this example it is just an Int but in the real code it is a Provider class) What am I doing wrong here? and why is x is an unresolved reference?

class Test
@Inject constructor(private val x: Int) {

companion object {
    var y: Int = 0

        @BeforeClass @JvmStatic
        fun beforeClass() {
            y = x * 2
        }
    }
}

Solution

  • A companion object is a static object associated with a class, not with an instance of a class.

    class Foo(val bar: Baz) {
        companion object {}
    }
    

    is similar to the following code in Java:

    class Foo {
        static class Companion { }
        static final Foo.Companion Companion = new Foo.Companion();
    
        final Baz bar;
        Foo(Baz bar) { this.bar = bar; }
    }
    

    This is why x is not in the variable scope of the companion object, just like you cannot access the bar field from the static class Companion. Your property y is actually a field in the Test.Companion class.

    I'm not sure what you're trying to do with the BeforeClass thing, since I'm not familiar with it. Hope my answer helps anyway.