I’d like to propose a feature where the compiler would warn users if they ignore the result of specially annotated functions. Here’s some examples of bugs:
val s = "Hello" s.substring(2) // Ignoring the result is always a bug or pointlessdata class Person(val firstName: String, val lastName: String)
val p = Person("Andrew", "O'Malley") p.copy(firstName = "Bill") // Bugval set = Sets.of("Hello") // Persistent set (e.g. from Dexx) set.add("there") // Bug
I see the number of cases of such bugs growing as immutable structures and functional approaches become mainstream.
I propose allowing functions to declare that their results must be used with a mustUse annotation. If they are not used the compiler will emit a warning.
mustUse fun String.substring(beginIndex: Int) : String = ...
- IntelliJ already has this feature in the Java plugin for String.substring(). Presumably the rule is hard-wired somewhere however
- I believe Rust has a “unused_must_use” lint mode coupled with a “#[must_use]” directive. It only seems to apply at a trait level, not a function level however.
Any thoughts? If the idea has any traction I can raise an issue for it.