AlexeyGorovoy
AlexeyGorovoy

Reputation: 800

Find usages of primary constructor of a Kotlin class

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?

Upvotes: 27

Views: 2672

Answers (5)

Mike Hanafey
Mike Hanafey

Reputation: 5643

If you put the word "constructor" before the "(" on the primary constructor then you can target this word for the usages search. This explains the importance of the position -- without the word you must click where to word would be.

Upvotes: 0

Dirk Hoffmann
Dirk Hoffmann

Reputation: 1563

... as time goes by ... and IntelliJ evolves ...

if I put the cursor somewhere in the class name and invoke Find Usages (Alt+F7) it finds all usages of the class.

but ...

if I put the cursor directly in front of the ( and invoke Find Usages (Alt+F7) it only finds calls to the constructor.

Upvotes: 0

Kirill Rakhman
Kirill Rakhman

Reputation: 43851

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.

Upvotes: 34

AlexeyGorovoy
AlexeyGorovoy

Reputation: 800

I'm sorry for so quickly answering my own question, but I guess I've found a solution. In two simple step:

  1. Double-click the name of a class to select it
  2. Ctrl+B to find usages (edit: Alt+f7 would also work)

I'm not sure it works in all cases, but it worked for me.

Upvotes: 21

Adam S
Adam S

Reputation: 16414

Since your "Find Usages" call (Alt+F7 on OSX) is from the Kotlin class name (which is also the constructor definition), you'll get more results than you would have if you'd done the same on a Java constructor - as you saw. If Find Usages didn't show usages of the class from this point, how else would you know where the class is used?

Doing this on one of my own Kotlin classes, I got the following:

enter image description here

Expanding "New instance creation" shows me constructor usage.

Upvotes: 3

Related Questions