Home > OS >  Property must be initialised even though type is defined in Kotlin
Property must be initialised even though type is defined in Kotlin

Time:06-09

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.

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 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

CodePudding user response:

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
  • Related