Lukasz Kalnik
08/23/2022, 8:51 AMval property in the init block of a class based on some Either value. However, whenever I use any of the Either related functions like fold or either.eager block (which take a lambda as parameter) and I try to set the class property inside the lambda I get the error "Captured member variables initialization is forbidden due to possible reassignment".
Is my only option really something like:
myProperty = if (either.isRight()) either.value else defaultValue
?simon.vergauwen
08/23/2022, 8:53 AMmyProperty = either.fold({ defaultValue }, { it })
This doesn't work?Lukasz Kalnik
08/23/2022, 8:53 AMsimon.vergauwen
08/23/2022, 8:53 AM.orNull() ?: defaultValue or getOrElse ?Lukasz Kalnik
08/23/2022, 8:53 AMmyProperty out of the lambda...simon.vergauwen
08/23/2022, 8:54 AMinline fun it should be perfectly valid.Lukasz Kalnik
08/23/2022, 8:54 AMeither.fold({ myProperty = defaultValue }, { myProperty = it })Lukasz Kalnik
08/23/2022, 8:55 AMstojan
08/23/2022, 8:55 AMetiher.fold({}, {}) and creating your class inside the lambda... that way your class doesn't have to know about EitherLukasz Kalnik
08/23/2022, 8:55 AMinit block is inside the classLukasz Kalnik
08/23/2022, 8:56 AMEither. I want to initialize the UI state of the viewmodel based on the value returned by the repository.Youssef Shoaib [MOD]
08/23/2022, 12:43 PMAT_MOST_ONCE or EXACTLY_ONCEsimon.vergauwen
08/23/2022, 12:47 PMsimon.vergauwen
08/23/2022, 12:58 PMfold since we need to specify AT_MOST_ONCE for both lambdas but the compiler now still won't now which one of the two lambdas will be executed, and that both will not be executed.
inline fun <E, A, B> Either<E, A>.fold(
error: (E) -> B,
transform: (A) -> B
): B {
contract {
callsInPlace(error, InvocationKind.AT_MOST_ONCE)
callsInPlace(transform, InvocationKind.AT_MOST_ONCE)
}
So it will complain that either.fold2({ myProperty = "defaultValue" }, { myProperty = it }) the second assignment is invalid since val can only be assigned once.simon.vergauwen
08/23/2022, 1:08 PMsimon.vergauwen
08/23/2022, 1:10 PMfold/transform the value and then assign in a single statement like the fix that we discussed above. myProperty = either.fold({ defaultValue }, { it }).Lukasz Kalnik
08/23/2022, 1:20 PM