:exploding_head: I'm having trouble with Kotlin + ...
# spring
m
🤯 I'm having trouble with Kotlin + Spring magic (
@Transactional
) in following code:
Copy code
class MyBoolean(var value: Boolean) {
    fun get(): Boolean = value
}

abstract class Foo {
    private val _hasError = MyBoolean(false)                                // <- line 16
    val hasError: Boolean get() = _hasError.get()
}

@Component
class MyFoo : Foo() {
    @Transactional
    fun doFoo() {
    }
}

class FooTest : SpringTest() {
    @Autowired
    lateinit var foo: MyFoo

    @Test
    fun `is null`() {
        assertThat(foo.hasError).isFalse                                    // <- line 33
        foo.doFoo()
    }
}
code/test above throws exception
Copy code
java.lang.NullPointerException: Cannot invoke "com.bitsafe.behi.admin.projections.MyBoolean.get()" because "this._hasError" is null

at Foo.getHasError(FooTest.kt:16)
at <http://FooTest.is|FooTest.is> null(FooTest.kt:33)
which doesn't make sense as
_hasError
should never be
null
? If I remove
@Transactional
from
doFoo
method everything works as expected. What's going on? BTW problem also disappears if I put stuff from
abstract class Foo
directly into
class MyFoo
(which I don't want).
c
In the test
foo
is declared as lateinit - but not initialized.
ah, its injected. perhaps put a breakpoint and see what things looks like.
m
good point with debugger
c
hmmm. the generated proxy (for @Transactional) set it to null. is this a recent Spring version that would understand it’s a Kotlin class (with non-null semantics)?
m
Spring Boot 2.7.2 with Kotlin 1.7.10 and/or 1.6.21
c
this link indicates that making the property open may address this. Are you using the Gradle koting/spring plugin to set objects to open? (this requires @Component on the classes to take effect)
m
ok if I change
private val _hasError
to
open val _hasError
it works
c
cool. Adding @Component to the abstract class my also do it.
(assuming the kotlin-spring plugin is in play)
m
yes adding @Component also fixed it. thanks a lot!
👍 1
s
you may also wanna consider the all-open/spring plugin