is there a compiler flag or something I can set to...
# getting-started
d
is there a compiler flag or something I can set to make sure that an expression that is supposed to return
Unit
has to return
Unit
? By being able to return anything when a
Unit
is expected I have created a bug in my code where some piece of side-effecting code wasn’t “run” to return
Unit
but the compiler didn’t pick it up because you can return anything if
Unit
is expected. 😞
s
Can you share a small code example? I think I have some idea of what you mean but it’s not totally clear to me.
d
Copy code
class Effect<A, B>(val f: (A) -> B)
fun effect(): Effect<Unit, Unit> = Effect { println("launch missiles") }
fun <A, B> runEffect(eff: Effect<A, B>, a: A): B = eff.f(a)
fun wontLaunchMissiles(eff: Effect<Unit, Unit>): Unit = run { effect() }
I want the compiler to tell me to write
run { runEffect(effect()) }
because I have returned an
Effect<Unit>
not a
Unit
FYI this is obviously contrived but we have an effects system that we use in-house and it effectively does something like this
👍 2
I understand that for certain types of coding there is a reasonable argument for not forcing
Unit
to be returned but for a functional style this return type indicates that you have done some side-effect and so by not returning it explicitly you are losing the ability for the compiler to tell you that you’ve made a mistake. I wondered if anyone knew of some linting rule or experimental compiler flag or something to disable this implicit
Unit
return?
s
I think basically this is the same issue as https://youtrack.jetbrains.com/issue/KT-12719, i.e.
effect()
returns a non-unit value so the IDE/compiler should always warn if it’s unused
The rule about using the last statement of a lambda function as its return value just doesn’t apply to Unit functions (see https://kotlinlang.org/docs/lambdas.html#lambda-expression-syntax). But I think this problem generalises beyond lambda functions anyway. A warning would be useful anywhere
effect()
is called without using its result.
d
yeah, it looks like KT-12719 would do it. However that is a harder problem to solve so might not happen any time soon 😞 I don’t think a ktlint rule would be possible because it can’t know the return type of the thing you want to be warned isn’t unit 😞
ok thanks anyway!
s
d
oh not heard of Detekt
I think I might have a go using that however unfortunately this rule requires an annotation. It will still be useful to put in places where I know something should always be used
s
I think you can also configure the detekt rule to inspect everything by setting
restrictToAnnotatedMethods
to false if you want. The configuration for that rule looks pretty flexible 👍
d
ah cool