Marcin Wisniowski
10/23/2024, 9:13 PMfun example(argument: Int?) {
val argument = argument ?: 5
...
}
But it generates the "name shadowed" lint warning. Is there an alternative that is better?ephemient
10/23/2024, 9:14 PMfun exmaple(argument: Int = 5)
?Marcin Wisniowski
10/23/2024, 9:15 PMMarcin Wisniowski
10/23/2024, 9:16 PMshowUserAvatar(avatar: Avatar?)
and the user might not have an avatar, in which case the function shows a default, but the caller can just pass in the avatar property without having to do a null check.ephemient
10/23/2024, 9:17 PMephemient
10/23/2024, 9:18 PMMarcin Wisniowski
10/23/2024, 9:18 PMephemient
10/23/2024, 9:18 PMMario Niebes
10/23/2024, 9:27 PMThis prevents the caller from passing in nullyou can also have a default on a nullable type
fun example(argument: Int? = 5) {
}
Marcin Wisniowski
10/23/2024, 9:33 PMshowUserAvatar(user.avatar)
and avatar
is nullable.ephemient
10/23/2024, 9:38 PMshowUserAvatar(user.avatar ?: _)
Ronny Bräunlich
10/24/2024, 9:50 AMshowUserAvatar(nullableAvatar: Avatar?) {
val avatar = nullableAvatar ?: DEFAULT_AVATAR
...
}
or
showUserAvatar(avatar: Avatar?) {
val avatarOrDefault = avatar ?: DEFAULT_AVATAR
...
}
would also be readable code, wouldn't it?Marcin Wisniowski
10/24/2024, 9:53 AMorDefault
for the internal version works indeed.loke
10/27/2024, 4:27 PMJacob
10/28/2024, 3:26 PMwould also be readable code, wouldn't it?It would be readable and more likely to be buggy. There are now 2 avatars and I might reference the wrong one later down
loke
10/28/2024, 3:33 PMJonathan Mandel
10/28/2024, 10:25 PMfun showUserID(uid: Int? = 5) {
...
}
works. You can pass in null or nothing and it behaves as expected.
Your code generates the shadowing warning because it is indeed shadowing the argument. That is,
val argument = ... creates another variable called argument that now occupies that namespace in this scope. It hides the parameter called 'argument'.
To do it your way, this would be better:
fun example(argument: Int?) {
val nonNullID: Int = argument ?: 5
...
}
That will eliminate the warning.Jacob
10/28/2024, 10:27 PMbobko
11/04/2024, 2:44 PMMarcin Wisniowski
11/04/2024, 3:16 PMloke
11/10/2024, 10:17 AM