user3706629
user3706629

Reputation: 229

Is possible in kotlin to assign delegate to property in init block?

Properties in kotlin can be initialized in init block:

val a: String
init {
    a = "aaa"
}

Can I initialize property by delegate in init block?

Upvotes: 1

Views: 448

Answers (2)

zsmb13
zsmb13

Reputation: 89548

Property delegation can only be done where the properties (or local variables, since 1.1) are declared, you can't do it later in an init block. You can see this being defined in the Kotlin grammar here:

property
  : modifiers ("val" | "var")
      typeParameters?
      (type ".")?
      (multipleVariableDeclarations | variableDeclarationEntry)
      typeConstraints
      ("by" | "=" expression SEMI?)?
      (getter? setter? | setter? getter?) SEMI?
  ;

There is no use explaining this entire part of the grammar, but you can quickly see that it describes property declarations, which always contains a val or a val at the beginning, and then there's the by of delegation somewhere afterward, followed by an expression describing the delegate.

There is only one other appearance of the by keyword in the grammar, which of course is when it's used for class delegation.

Upvotes: 2

tynn
tynn

Reputation: 39843

You can just delegate to another property.

class Foo {
    private val del: ReadWriteProperty<Foo, String> 
    init { del = Delegates.notNull() }
    val bar by del
}

Upvotes: 1

Related Questions