iex
05/15/2019, 3:19 PMclass A {
val foo = "hello"
}
class B(a: A) {
init {
a.foo.bar // null pointer
}
}
`
streetsofboston
05/15/2019, 3:20 PMbar
? Where does bar
come from?iex
05/15/2019, 3:20 PMfoo
isn't a string. It's just a method of the fieldiex
05/15/2019, 3:21 PMa.foo
is null
streetsofboston
05/15/2019, 3:21 PMstreetsofboston
05/15/2019, 3:21 PMB
class is called.iex
05/15/2019, 3:23 PMiex
05/15/2019, 3:25 PMclass 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
Marko Mitic
05/15/2019, 3:27 PMstreetsofboston
05/15/2019, 3:28 PMfoo
has not yet been initialized when you access it in `B`’s constructor blockribesg
05/15/2019, 3:30 PMstreetsofboston
05/15/2019, 3:33 PMopen 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… 🙂iex
05/15/2019, 3:37 PMiex
05/15/2019, 3:37 PMStephan Schroeder
05/16/2019, 8:54 AMclass B(a: A) {
init {
println(a.foo.length)
}
}
class A {
val foo = "hello"
val b = B(this)
}
B(A())
iex
05/16/2019, 6:58 PM