DEV Community

hamid3d
hamid3d

Posted on

why kotlin complie wrong code?

Hi
In kotlin we should initialize members of class or will assign latter or even make member nullable but I want to show an issue in kotlin compiler.

At first see this class

Image description

As you see we have error that says

Property must be initialized or be abstract

okay I assign a value to this member in init then error gone because kotlin compiler understands that the member is initialized and it is not null

Image description

okay I remove initialize in init and I make a setter and getter for member as you see we have not error but without initialization

no error here

Image description

And it will compile by kotlin but we know it is wrong and by execution we will get error because it is really obvious but I do not know why kotlin accepts to compile this code (here getter labels as recursive call)

execution error

Image description

Top comments (1)

Collapse
 
unthrottled profile image
Alex Simons

The code is valid, however the IDE is telling you that what is written isn't going to work. See how age is highlighted and there is a recursion icon in the gutter. When you hover over age you get Recursive property accessor

The compiler is there to help you with any syntax mistakes, its job isn't to help you with the semantics of your code. That's where the IDE can help you. It can tell you that the code you wrote isn't going to work.