Skip to content

Extend TernaryOperatorsShouldNotBeNested with pattern matching #158

Open
@pstreef

Description

@pstreef

What problem are you trying to solve?

Pattern matching switch expressions can be used to simplify nested ternaries

Describe the solution you'd like

"""
  import java.util.Set;
  import java.util.Arrays;
  import java.util.List;
  import java.util.stream.Collectors;
  class Test {
    public Set<String> makeASet() {
       List<String> s = Arrays.asList("a","b","c","nope");
       return s.stream().map(item -> item.startsWith("a") ? "a" : item.startsWith("b") ? "b" : "nope").collect(Collectors.toSet());
    }
  }
  """,
"""
  import java.util.Set;
  import java.util.Arrays;
  import java.util.List;
  import java.util.stream.Collectors;
  class Test {
    public Set<String> makeASet() {
       List<String> s = Arrays.asList("a","b","c","nope");
       return s.stream().map(item ->
        switch (item) {
          case String st && st.startsWith("a") -> "a";
          case String st && st.startsWith("b") -> "b";
          default -> "nope";
        }
       ).collect(Collectors.toSet());
    }
  }
  """

Metadata

Metadata

Assignees

No one assigned

    Labels

    enhancementNew feature or request

    Type

    No type

    Projects

    Status

    Backlog

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions