I use Code A as shown below frequently.
Unfortunately, I can't understand the syntax structure for private set
completely, so I get the following error when I replace Code A with Code B.
Function invocation 'set(...)' expected
What is the full syntax structure for private set
in Kotlin?
Code A
var isRecording by mutableStateOf(false)
private set
Code B
var isRecording by mutableStateOf(false) private set
CodePudding user response:
This is the relevant grammar, from https://kotlinlang.org/docs/reference/grammar.html :
propertyDeclaration (used by declaration)
: modifiers? ('val' | 'var') typeParameters?
(receiverType '.')?
(multiVariableDeclaration | variableDeclaration)
typeConstraints?
(('=' expression) | propertyDelegate)? ';'?
((getter? (semi? setter)?) | (setter? (semi? getter)?))
;
propertyDelegate (used by propertyDeclaration)
: 'by' expression
;
My take on it is that the new line is needed because otherwise it assumes the private set
is part of the expression
in the propertyDelegate
.
And indeed, it is actually possible to write a functional one-liner where the private set
is part of the expression. this is correct functional code:
val set = 0
var isRecording by mutableStateOf(false) private set
public infix fun <A, B> A.private(that: B): A = this
But I would highly recommend to never write such code haha.
CodePudding user response:
if you want how to initialize a set in kotlin, try this. This link also has necessary details for other collection datatypes. hope it helps. here's a sample -
private var immutableSet = setOf(6,9,9,0,0,"Mahipal","Nikhil")