https://kotlinlang.org logo
Title
i

iex

05/15/2019, 3:19 PM
class A {
    val foo = "hello"
}
class B(a: A) {
    init {
        a.foo.bar // null pointer
    }
}
`
s

streetsofboston

05/15/2019, 3:20 PM
bar
? Where does
bar
come from?
i

iex

05/15/2019, 3:20 PM
my
foo
isn't a string. It's just a method of the field
point being
a.foo
is
null
s

streetsofboston

05/15/2019, 3:21 PM
Could you post a snippet of the actual code so that we can see what might wrong?
E.g. also how the constructor of the
B
class is called.
i

iex

05/15/2019, 3:23 PM
hm yeah I can't reproduce it with this snippet. Will play a bit with a scratch and post if I can't figure it out
ok, so the problem is this
class B(a: A) {
    init {
        println(a.foo.length)
    }
}

class A {
    val b = B(this)
    val foo = "hello"
}

B(A())
And the solution is to move the line with
val foo = "hello"
above the one that's initializing
B
m

Marko Mitic

05/15/2019, 3:27 PM
circular dependencies are a b**ch
s

streetsofboston

05/15/2019, 3:28 PM
yes, this makes sense.
foo
has not yet been initialized when you access it in `B`’s constructor block
r

ribesg

05/15/2019, 3:30 PM
Nothing unexpected here
s

streetsofboston

05/15/2019, 3:33 PM
Try something like this. It won’t run:
open class A(val b: B)
open class B(val a: A)

object objectA : A(objectB)
object objectB : B(objectA)
If you change it to this:
open class A(val b: B?)
open class B(val a: A?)
Then the value of
objectA.b
or
objectB.a
may or may not be null… 🙂
i

iex

05/15/2019, 3:37 PM
yeah I understand the reason... bit hairy 😄
thanks for the help in any case!
s

Stephan Schroeder

05/16/2019, 8:54 AM
you probably did this already, if not, just exchange the lines in A
class B(a: A) {
    init {
        println(a.foo.length)
    }
}

class A {
    val foo = "hello"
    val b = B(this)
}

B(A())
i

iex

05/16/2019, 6:58 PM
@Stephan Schroeder yes I did 😄