#NotNull, #Nonnull etc. all don't work in IntelliJ IDEA - intellij-idea

I have tried annotating a field with
org.checkerframework.checker.nullness.qual.NonNull
org.jetbrains.annotations.NotNull
javax.annotation.Nonnull
And in all cases, assigning a null to it generates no complaints from IntelliJ 2016.2.
public class GreetingController {
#NotNull Integer x = 3;
public void foo() { x = null; }
}
That all compiles fine according to IntelliJ.
This page from IntelliJ specifically states that "IntelliJ IDEA highlights the problems “on-the-fly”, so you can see the inspection results right in the editor." I have even copied the example code (public class TestNullable) into my editor and it produces no errors.
This other page from IntelliJ states you can change the annotations it responds to. So I chose javax.annotation.Nonnull and made sure that was the one I was using in my code, still no luck.
To be clear, what I'm hoping for, and what I understand should be provided, is that the editor window / compiler alerts me to the problem (I am not looking for a runtime check, NullPointerException already works fine at runtime.)
In case it didn't work in real time, I tried "Rebuild Project".
I'm sure this must work, what am I doing wrong?
I have uploaded an example of this not working here: ZIP download.

As I can see from your screenshots and the sample project, IntelliJ IDEA does show you the warnings. Note that these warnings are shown by the code inspections which are running on the fly and will be displayed in the editor or in the Analyze | Inspect Code results. These warnings will not be displayed by the compiler.
Note that you can configure the warnings highlighting if needed (for example add the underwave effect):
You can also change the severity of the inspection (like to Error):
You may also want to vote for this feature request:
IDEA-78625 Provide inspection severity level that will work like validation and abort compilation
As a bonus, pay attention to the javax.annotation.Nullable annotation, it may be not what you think it's for, see this comment and the documentation. For some years IntelliJ IDEA has incorrectly suggested to use this annotation, while the correct one for such cases would be javax.annotation.CheckForNull:
This annotation is useful mostly for overriding a Nonnull annotation.
Static analysis tools should generally treat the annotated items as
though they had no annotation, unless they are configured to minimize
false negatives. Use CheckForNull to indicate that the element value
should always be checked for a null value.

"Settings" > "Inspections" > "Probable Bugs" > "Constant conditions & exceptions"
Tick the first option: "Suggest #NotNull annotation for methods that possibly return null and report nullable values passed to non-annotated parameters.
Click "Configure Annotations". By default, Intellij will use their own annotations from org.jetbrains.annotation. I was using the more general (my own opinion) annotations from javax.annotation.
I set Nullable to: javax.annotation.Nullable
I set NotNUll to : javax.annotation.NotNull
In order to set these new options, you must click them, then click the tiny checkmark button to the right to set it. Selecting the javax.annotation annotations then hitting "OK" will NOT lock in the new settings, you must use the checkbox button.
After successfully specifying javax.annotation.Nullable and javax.annotation.NotNull, the code correctly highlighted null problems.

The best that this can do is offer up warnings. It will not stop compilation from happening, since the annotations do not prohibit or preclude code compilation from taking place.
Be sure that you have the appropriate inspections enabled in your IDE, and be sure that you remain aware of what parameters you're passing into your method. The IDE can at best warn you, but it can't really stop you.
Alternatively, introduce a unit test to fail if that method receives a null parameter, and rely on that to ensure that you're not breaking code or expectations.

Related

"Convert property getter to initializer" - but they aren't the same thing, are they?

I'm using IntelliJ with a mixed Java/Kotlin project. In one of my Kotlin files, I have this property:
override val value: String
get() {
return webElement.getAttribute("value")
}
IntelliJ's light bulb offers to "Convert property getter to initializer", which changes the code to this:
override val value: String = webElement.getAttribute("value")
To me, it seems like this isn't a simple refactoring, but a significant code change. What I think is happening is:
In the first version, the value property is retrieved when I call value.
In the changed version, the value property is set immediately when the class instance is constructed, and then never changes for that class instance.
But maybe this is more like C# expression-bodied members, which use a lambda arrow => instead of braces and return but otherwise work exactly the same way.
So...which is it? When will the second version of the code initialize?
You are correct regarding these statements:
In the first version, the value property is retrieved when I call value.
In the changed version, the value property is set immediately when the class instance is constructed, and then never changes for that class instance.
IntelliJ's light bulb offers to "Convert property getter to initializer" because it is just an option available. Light bulb only highlights the actions you can do with a selected piece of code.
IntelliJ does not try to tell you that "property initializer" and "property getter" are equal. What it tells you is that you can convert one to the other if you wish to.
I agree that it is confusing, especially considering this quote from IntelliJ Idea documentation:
As soon as the IDE finds a way to alter your code, it displays a yellow bulb icon in the editor next to the current line. By clicking this icon, you can view intention actions available for this unit of code. Intention actions cover a wide range of situations from warnings to optimization suggestions. You can view the full list of intentions and customize them in the Settings/Preferences dialog ⌘,.
Having this in mind it could appear that your code is either can be optimized or has a warning.
The answer
When will the second version of the code initialize?
... immediately when the class instance is constructed.
You are correct.

Suppress NOTHING_TO_INLINE warning globally

I have a function in Kotlin that I want to inline despite not being high-order.
I find that through out the project I have numerous occurrences of such scenario.
Therefore, to ignore compiler warnings about using inline functions, I have to use lots of Suppress("NOTHING_TO_INLINE") annotations through out my project and it's starting to bother me.
Is there any way to block this warning for the whole project by, for instance, a compiler option?
I'd like to know how to do this in IntelliJ IDEA.
It doesn't look like it's possible to disable the inspection globally. I can't find a setting in IntelliJ at least. You can, however, disable the inspection for an entire file:
#file:Suppress("NOTHING_TO_INLINE")
If you press ALT+Enter on the warning, you'll get an option to suppress it which just contains suppressing for the function, class (if it's in one), or for the entire file. Any inspections you can disable usually has a "Disable inspection" option on this list (which NOTHING_TO_INLINE does not have).
You can, however, disable the warnings when compiling (but it does not affect the inspection; you'll still see warnings while editing) by adding suppressWarnings to the compileKotlin task. Note that this disables ALL warnings, not just specific ones.
compileKotlin {
kotlinOptions.suppressWarnings = true
}

IntelliJ type error when using Geb static content DSL with parameters

Whenever I use a static-content defined closure that takes parameters, IntelliJ will complain that the types do not match (even if I specify the type inside the closure).
For example, if I use this static content block:
static content = {
myModule { $('myModule').module(CustomModule) }
namedModule { String name -> $(".$name").module(CustomModule) }
}
Both of the above items can be used successfully in my tests, but if I was to use 'namedModule' in one of my tests as follows:
page.namedModule("moduleName").moduleMethod("blah blah blah")
IntelliJ will highlight the parameter "moduleName" in yellow with the error:
'namedModule' cannot be applied to '(java.lang.String)'
We are trying to refactor our tests in a way that means you can navigate through the code easier (e.g. avoiding any Geb/Groovy 'magic' that IntelliJ can't resolve), and this is one of the last remaining issues preventing this from being possible.
This is a known limitation to Geb support in IntelliJ. IntelliJ always treats content definitions as properties of pages and modules even though they can be parametrised. Given that Geb support in IntelliJ is open sourced we could probably add support for this.
In the mean time, as a workaround you can use methods for parametrised content instead of content definitions and IntelliJ will be able to understand these and be able to refactor them:
void namedModule(String name) {
$(".$name").module(CustomModule)
}
There are some caveats, though:
you will loose ability to use content definition options; if you need to use these for a content definition then I suggest creating a parameterised "private" content definition (for example with a _ at the beginning of the name) that you will only ever access from within the page or module
RequiredPageContentNotPresent will not be thrown even if the returned content is empty; to work around it you will either need to add manual verification to each such method or use a strategy outlined in the first bullet point with using "private" content definitions

switching between languages in same file

I recently attended a user group meeting where the IntelliJ representative was demonstrating version 13.
He demonstrated how to switch the code completion view of a file. I do not exactly remember what the file extension of this particular file was, probably java.
The concept was that if the file is html with embedded javascript he could then switch the code completion between html and javascript with a shortcut. If he says treat the file as html then all code in file was treated for code completion purposes as html, and vice versa for javascript.
Does anybody know what shortcut he might have been using to enable the language switch?
Sounds like you may be referring to the IntelliLang feature. IntelliJ IDEA can be aware of other languages embedded within a file.
A simple example is in an HTML file that has CSS and JavaScript.
Notice when I am inside the HTML markup:
or inside an HTML element:
The code complete shows HTML completion options. However, when I am inside the style attribute, I get CSS code completion:
I also get CSS code completion if I am inside a <style> element. So even though I am in an HTML file, I see CSS code completion because of my location.
Same case with JavaScript. When I invoke code completion inside a <script> element, I get JavaScript completion, even though I am in an HTML file.
Anytime IntelliJ IDEA can determine that another embedded language is present, it provides, via IntelliLang, the appropriate syntax highlighting, error highlighting, and code completion. The same holds true for Java. Notice here that IDEA knows the method I am competing takes an SQL statement and therefore highlights the String value using SQL highlighting, and provides SQL code completion:
So even though I am in a .java file, I get SQL code completion. The reason is that IntelliLang comes pre-configured knowing the embedded language of some methods. You modify them, or add more, in File > Settings > [Project Settings] > Language Injections.
In addition, you can use an annotation to tell IntelliJ IDEA (as well as developers looking at the code) that a String must be valid in a particular language. For example, I can annotate a String field, variable, or parameter, to indicate it must be valid HTML:
Notice I get HTML syntax highlighting, HTML code completions, and the CSS color shows in the left gutter. If I annotate a method parameter, then any time I call the method, I get the appropriate syntax highlighting, code completion, and error/warning highlighting:
The #Language annotation is inside the annotations.jar that is contained in the redist directory inside the IntelliJ IDEA installation directory. It is also available in maven central, or IDEA will offer to attach it as a Library if you use the annotation without it being attached.
IntelliLang and the #Language annotation supports a large number of languages. Just use code Completion inside the quotes after typing #Language("") to see a list. (Inline search works in the list as well.) One of the most useful is Regexp. For example, if you have a method that expects the string passed in to be a valid Regular Expression, annotating it as such will give anyone that calls it Regex code completion and error highlighting if they are passing in an invalid Regex pattern. Even for developers using other IDEs it is useful as a form of documentation.
As for a shortcut to change the the language on the fly for code completion, the only thing I can think that you might be referring to is the "Inject Language" intention. If I am entering a String value, and I bring up the quick-fix/intention menu via Alt+Enter, I am given an option to inject a language:
If I select that, IntelliJ IDEA will ask me what language I want to use:
After making my selection, IntelliJ IDEA will give me temporary language injection (including code completion) for the selected language.
It also gives me an option to add the #Language annotation for permanent injection.
To the best of my knowledge (as a 10 year IntelliJ IDEA user) that is the only way to switch code completion language types. So hopefully that is what you are looking for. To me, IntelliLang is one of the coolest features in IntelliJ. (It actually started as a third party plug-in and JetBrains then absorbed it into the product.)

Code not working once deployed

I've got the following code in a thread in my application:
while (true) {
if (ready) {
progressIndicatorController.value++;
return;
}
}
The ready variable is changed from a delegate method. This code works great when I open the application by clicking the "Run" button in Xcode's toolbar. However, if I open this application's .app (which I create by clicking Product > Archive and then following the steps) this code somehow doesn't work anymore.
progressIndicatorController.value is never incremented and this if-statement never evaluates to true. What could cause this problem?
This is probably caused by optimization from the compiler.
When you build with Archive, XCode enabled optimization in the compiler that could throw this kind of code away. I think setting the ready variable to volatile could fix your problem, altough if I were you I'd just try to rewrite it so it doesn't trigger this problem.
You can test with optimization turned on by choosing Edit Schemes in the scheme dropdown. Then set Build Configuration to Release in the Run MyApp.app. Don't forget to set it back to Debug when you're done though, as the debugger gets somewhat confused when optimization are on (i.e. you can't see the value of most variables, some breakpoints may behave erratically, etc...)