IntelliJ IDEA
 
Get IntelliJ IDEA

Tutorial: Structural search and replace in Kotlin

Last modified: 11 October 2024

Structural search and replace is a powerful tool that can search for a specific pattern in code and replace it in an automated way.

In this tutorial we will get acquainted with templates and filters, modify a predefined template, and then create a code inspection based on it.

The functionality covered in this tutorial is by no means the exhaustive list of what Structural Search and Replace can do. Our goal is to get you started. After that, you can explore various templates, filters, and options and combine them to create your own specific searches.

For the tutorial, we will use the following code:

Now, let's return to our structural search dialog to alter the predefined template a bit.

With Structural Search, we can run some interesting searches. Let's choose another existing template (Method calls) as our example. Assume we're doing this search to replace all print statements with logging calls and exclude all calls that do not have a String as the argument.

We can save this template for later use if we need.

We can also use our template as an inspection, so when we come across the same code, we'll see a warning and can quickly replace the code.