5

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.

5
  • 1
    Are you looking for lateinit var? Commented Apr 17, 2018 at 10:43
  • I just want to assign value to "C" in other class, before assign nothing in "c" variable Commented Apr 17, 2018 at 10:46
  • You can't late-initialize a val. Commented Apr 17, 2018 at 10:46
  • so Kotlin documentation fail ? Commented Apr 17, 2018 at 10:46
  • Have you tried using 'by lazy {}' to perform a kind of lateinit on the variable? val c:Int by lazy { ... } Commented Apr 17, 2018 at 13:51

3 Answers 3

8

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
}
Sign up to request clarification or add additional context in comments.

Comments

2

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.

Comments

-2

For val you need to do the declaration and the assignment together.

For your case, this variable needs to be modified after the declaration section, therefore var c: Int will be better.

1 Comment

"For val you need to do the declaration and the assignment together." - no you don't, please see my answer.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.