Hi. I'm using delegates outside of fields. This pr...
# announcements
e
Hi. I'm using delegates outside of fields. This produces a warning
ASSIGNED_BUT_NEVER_ACCESSED_VARIABLE
upon assignment only. While that warning is technically correct, and makes sense, it would be nice to remove it. How? My code looks like this:
Copy code
var ok by okProp
ok = true
where setting
ok
will have side effect. Example: https://pl.kotl.in/81eXfsXLG (press run to get the warnings). On a side note, the decompiled code looks like this:
Copy code
KProperty var1 = $$delegatedProperties[0];
ReadWriteProperty ok = okProp;
ok.setValue((Object)null, var1, true);
As one would expect the variable will be both accessed and assigned, just not in Kotlin
d
I’m not sure I understand the use case. The warning is because
ok
is instantiated but never used. Adding
if (ok) println(“ok”)
Makes the warning go away And the same warnings appear with
Copy code
var t: Boolean
t = true
I think also if you
return
ok from some function it would similarly not provide the warning. Essentially you’re instantiating this variable without any purpose?
e
It has purpose, since it has side effects. Imagine the delegate is passed into a function, and inside that function
by
is used only to trigger it
d
I am still not seeing why a delegate with side effects instead of a lambda or similar https://pl.kotl.in/IA98W8-qm That said, I suppose you could suppress the warning if you really want to use delegate and don’t want the warning https://pl.kotl.in/3Dp2hzVcP Just trying to understand the use case to suggest something that wouldn’t produce a warning to begin
e
That's a good solution, thanks. If you wonder about why I would pass around a delegate instead of a lambda; it's handy. I pass it from a library without knowing if a consumer would listen or set the value. I also support multiple listeners and binding. And it works very well in JavaFX (if consumer uses that). Maybe it's an anti-pattern, or an anti-pattern to be, but from my point of view it's neat
👍 1
d
You’d want to suppress UNUSED_VALUE if you want to suppress the second warning https://pl.kotl.in/Q3Ffo8WC2
e
Got it. Thank you
e
This comes up a lot in multiplatform Kotlin Gradle where you typically see things like:
Copy code
val commonMain by getting
With
commonMain
not being used after the declaration
e
Yeah isn't that default in the build.gradle.kts (template) file when creating a new project? I'm not sure if those lines are required though, would it fail if removed? As in the template have them just in case
e
I think there are side effects to the delegate, so IIRC it is required
e
Did a quick test. By having code in "commonMain" all I needed to do to support JavaScript was to have
js
under
kotlin
. I could safely remove
val jsMain by getting
. But yes it could have side effects, very similar to my case