Reputation: 229
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
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
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