Reputation: 11
class A
{
val b:B
val at:String
init
{
b=B(this)
at="A's text"
}
}
class B(a:A)
{
val bt:String
init
{
bt= if(a.at!=null) a.at.replaceFirst("A's","B's") else "else's text"
}
}
This code will generate a warning
Condition 'a.at!=null' is always 'true'
but actually the condition 'a.at!=null' is always false.
Upvotes: 0
Views: 1000
Reputation: 5214
This is already reported 3 years ago, as KT-10455, "Kotlin allows use of class members before initialization, leading to runtime exceptions, including NPEs on non-null types".
For temporarily fix, you can just swap the two lines in init
in class A
, make sure A.at
is defined before used.
class A
{
val b:B
val at:String
init
{
at="A's text"
b=B(this)
}
}
Upvotes: 2
Reputation: 30625
First you need to initialize variable at
and then b
:
class A
{
val b:B
val at:String
init
{
at="A's text"
b=B(this)
}
}
Upvotes: 0