https://kotlinlang.org logo
#arrow
Title
# arrow
k

Kev

10/17/2023, 2:14 PM
If I have some
data class ApplicationError(val cause: ApplicationError?)
, is there a neat way to flattern this which my potentially be something like
val cause = error.cause.cause.cause.cause.cause.cause.cause.cause
illustrating how long the chain may be
y

Youssef Shoaib [MOD]

10/17/2023, 3:04 PM
This will cause an infinite loop in case of a cycle, but:
Copy code
tailrec fun ApplicationError.rootCause(): ApplicationError? = cause?.rootCause()
d

Davio

10/17/2023, 4:03 PM
I don't think there can be a loop since the nested ApplicationError has to be passed during construction, so it has to already be initialized before this one, which means it can't have a nested ApplicationError that we're currently constructing. If the
val
was a
var
then yes, there could potentially be a loop.
k

Kev

10/17/2023, 4:04 PM
I was thinking of having a function recursively call itself until a null cause is hit, seeding into an arraylist, but it feels wrong
y

Youssef Shoaib [MOD]

10/17/2023, 4:06 PM
@Davio Oh yes I see what you mean. Agreed, I don't think there's any way to get a cycle out of it. @Kev that's what my solution kind of does, but it uses tailrec so no real recursion, and instead of seeding into an array list, theoretically you could make a sequence out of it and convert that to a list, but my solution is just easier I think
2 Views