Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Variable without initializer in Kotlin

Tags:

kotlin

How to implement variable without initializer ?

I found in Kotlin documentation:

val c: Int  // Type required when no initializer is provided
c = 3       // deferred assignment

but this does not work. IDE requires to make a initializer.

like image 996
jackfield Avatar asked Apr 17 '18 10:04

jackfield


2 Answers

If you're declaring a top-level property, you need to initialize it as part of the declaration. If you're declaring a local variable, you can initialize it later:

fun foo() {
    val c: Int
    c = 3
}
like image 120
yole Avatar answered Nov 15 '22 07:11

yole


I just want to assign value to "C" in other class

val can be used in two ways (counting 2 and 3 together):

  1. For local variables, in which case assigning in other class makes no sense at all. The documentation you quote refers to this case.

  2. For concrete properties, in which case they can be initialized separately from the declaration, but only in an init block of the class they are declared in.

  3. For abstract properties. But in this case you can't assign them from other class, but only implement these properties.

like image 32
Alexey Romanov Avatar answered Nov 15 '22 09:11

Alexey Romanov