Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find usages of primary constructor of a Kotlin class

Tags:

Imagine you have a super important and widely-used class in your Kotlin-based project. It has the only constructor which is defined like that:

class MyAwesomeManager(argOne: String, argTwo: String)

For some reason, you need to quickly find all uses of its constructor. You're using Android Studio (or Intellj IDEA).

But... pressing Ctrl + LMB on its name gives a ton of rubbish results - uses in imports, companion object's fields calls etc. All the uses of a class, but not the constructor. The same for putting a cursor on its name and hitting Alt + F7.

So, how do I find all and only the usages of this primary constructor?

like image 468
AlexeyGorovoy Avatar asked Sep 15 '17 10:09

AlexeyGorovoy


People also ask

What is the use of primary constructor in Kotlin?

The Kotlin primary constructor initializes the class, whereas the secondary constructor helps to include some extra logic while initializing the class.

How do you call a primary constructor in Kotlin?

In Kotlin, you can also call a constructor from another constructor of the same class (like in Java) using this() .

What is difference between primary constructor in Kotlin?

A class in Kotlin can have at most one primary constructor, and one or more secondary constructors. The primary constructor initializes the class, while the secondary constructor is used to initialize the class and introduce some extra logic.

What is the use of init in Kotlin?

Kotlin initThe code inside the init block is the first to be executed when the class is instantiated. The init block is run every time the class is instantiated, with any kind of constructor as we shall see next. Multiple initializer blocks can be written in a class. They'll be executed sequentially as shown below.


1 Answers

You should put the caret next to the opening parenthesis of the primary constructor but not right before the first parameter. Possibly add a space or line break:

class MyAwesomeManager<caret>(argOne: String, argTwo: String)
//also works
class MyAwesomeManager(<caret> argOne: String, argTwo: String)

then invoke Find Usages. This should give you only the usages of the constructor invocation.

If there are no parentheses because the class has a default zero-argument constructor, you can temporarily add () after the class name, then proceed as above.

like image 89
Kirill Rakhman Avatar answered Sep 27 '22 20:09

Kirill Rakhman