Uploaded image for project: 'Rules Repository'
  1. Rules Repository
  2. RSPEC-6212

Local-Variable Type Inference should be used

    Details

    • Type: Code Smell Detection
    • Status: Active
    • Resolution: Unresolved
    • Labels:
    • Message:
      Declare this local variable with "var" instead.
    • Highlighting:
      Hide

      Variable declaration type.

      Show
      Variable declaration type.
    • Default Severity:
      Info
    • Default Quality Profiles:
      Sonar way
    • Covered Languages:
      Java
    • Remediation Function:
      Constant/Issue
    • Constant Cost:
      0min
    • Analysis Scope:
      Main Sources

      Description

      In Java 10 Local-Variable Type Inference was introduced. It allows you to omit the expected type of a variable by declaring it with the var keyword.
      While it is not always possible or cleaner to use this new way of declaring a variable, when the type on the left is the same as the one on the right in an assignment, using the var will result in a more concise code.

      This rule reports an issue when the expected type of the variable is the same as the returned type of assigned expression and the type can be easily inferred by the reader, either when the tye is already mentioned in the name or the initializer, or when the expression is self-explained.

      Noncompliant Code Example

      MyClass myClass = new MyClass();
      
      int i = 10; // Type is self explained
      
      MyClass something = MyClass.getMyClass(); // Type is already mentionned in the initializer
      
      MyClass myClass = get(); // Type is already mentionned in the name

      Compliant Solution

      var myClass = new MyClass();
      
      var i = 10;
      
      var something = MyClass.getMyClass();
      
      var myClass = get();
      

      See

        Attachments

          Issue Links

            Activity

              People

              • Assignee:
                Unassigned
                Reporter:
                quentin.jaquier Quentin Jaquier
              • Votes:
                1 Vote for this issue
                Watchers:
                2 Start watching this issue

                Dates

                • Created:
                  Updated: