aballano
05/09/2022, 11:35 AMfun <T> something(f: () -> T): T
and I would like for the compiler to fail if I try to do this:
val unit: Unit = something {
1
}
The problem with this is that if we would have something like a Flow inside or any other complex type that we forgot to execute/unwrap/whatever, this would be a bug in the codebase, for example:
val unit: Unit = something {
flowOf(1)
}
If this would fail as I would expect it to, I would notice that I forgot to collect my flow, but instead is accepting a Flow or any type as Unit, is there a way to enforce this somehow?wasyl
05/09/2022, 11:51 AMUnit
type, which would have precedence over non-unit variant?
@JvmName("somethingReturningUnit")
@Deprecated(message = "Something must return a non-unit value", level = DeprecationLevel.ERROR)
fun something(fn: () -> Unit): Nothing = error("Shouldn't happen")
But you may have to explicitly declare typed arguments for non-unit usages 😕aballano
05/09/2022, 11:52 AMwasyl
05/09/2022, 11:53 AMaballano
05/09/2022, 11:54 AMwasyl
05/09/2022, 11:57 AMenforce type checkingtype checking works as expected here, if a function returns
Unit
then the generic type resolves to Unit
, and if you explicitly define the type as Unit
that’s perfectly valid as well.
My suggestion was to trick the compiler by making it pick an invalid function by utilizing the fact that a function with more concrete declaration (with an explicit Unit
) will be picked over the generic one, as far as I know. It has drawbacks, but it does enforce you don’t use a Unit
return type, doesn’t it?aballano
05/09/2022, 12:05 PMtype checking works as expected hereI don't agree, I'm not returning unit here
val unit: Unit = something {
1
}
I'm returning an Int, so there's an implicit conversion from what I'm returning vs what I'm expecting (Unit), which should result in a compiler error instead of implicitly converting it
My suggestion was to trick the compilerThe problem here is that I cannot just duplicate or workaround every single function doing something similar just because now the compiler thinks this is fine, which wasn't before in previous Kotlin versions
wasyl
05/09/2022, 12:09 PMaballano
05/09/2022, 12:10 PMTim Oltjenbruns
05/12/2022, 12:47 PM-Xenable-builder-inference