Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Property must be initialised even though type is defined in Kotlin

I am not sure Stack overflow will like this question. I am learning Kotlin and trying to declare a basic variable without any class.

This is the simplest example.

I now understand why the compiler won’t accept it, says it must be initialised. But if I put it inside the main function, then it works fine.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

I saw this tutorial on W3Schools and it says you dont have to initialise the variable if you declare its type? Well I have and it still is forcing me to initialise it
https://www.w3schools.com/kotlin/kotlin_variables.php

enter image description here

It’s a simple variable in a file no class:

/**
 * Number types:
 * This is the most important, and we should be able to go over it quick.
 * We start from the smallest to the biggest
 */

var byteEg: Byte;

Even inside a class it doesn’t work:

class Variables{
    var byteEg: Byte;
}

When I try latentinit it gives an exception: ‘lateinit’ modifier is not allowed on properties of primitive types

>Solution :

What W3Schools fails to mention is that it only holds true for variables that are not top level. So inside functions like

fun someFunction() {
    var byteEg: Byte
}

if you want to do it with top level declarations you can mark it as lateinit like

lateinit var byteEg: Byte
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading