Øyvind Holmstad Øyvind Holmstad - 3 months ago 11
Scala Question

How to find usages of a scala apply function in a class-instance in IntelliJ?

If I call an apply method from an instance of a Scala class

object Main {
def main(args: Array[String]): Unit = {
val a = new A(2)
a(2)
a(10)
}

class A(a: Int) {
def apply(a: Int): A = new A(a)
}
}


i am not able to find its usages with Alt + F7 or Ctrl+click.

Is there any way to find usages of a scala apply method in IntelliJ?




EDIT: In the first rendition of this question I did not understand that this is only a problem for apply-method for instances of classes. It works for apply-method in companion objects, as @sebszyller demonstrated below.

This is probably a bug in IntelliJ. Closing the question.

Answer

The following snippet works for me.

object Main {
  def main(args: Array[String]): Unit = {
    val a1 = A(1)
    val a2 = A(2)
  }

  class A(a: Int)
  object A {
    def apply(a: Int): A = new A(a)
  }
}

Ctrl-Click gives me a list that shows both A(1) and A(2). Cannot show the screenshot at the moment, unfortunately.

Works as well with your example; gives me a list of two usages as well.

object Main {
  def main(args: Array[String]): Unit = {   
    val eleven = Add10(1)
    val twelve = Add10(2)
  }

  object Add10 {
    def apply(a: Int): Int = a + 10
  }
}

I'm on 2016.2 now but I have been using the option for as long as I can remember.

UPDATE:

I figured this out. Consider the following snippet:

object Main {
  def main(args: Array[String]): Unit = {
    val a = new A(2)
    val b = new A(10)

    val a1 = a(2)
    val a2 = a(2)
    a.doSthElse

    val b1 = b(10)
    val b2 = b(10)

    val apply1 = a.apply _
    val apply2 = b.apply _ 
    val apply3 = a.apply(10)

    val tenFromA = apply1(10)
    val tenFromB = apply2(10)


  }

  class A(a: Int) {
    def apply(a: Int): A = new A(a)

    def doSthElse = println("sth else")
  }
}

It seems that apply is linked to the instance of the class and not the definition itself. In the following snippet, if you click on a it will show all you all the usages: a(2) twice, a.doSthElse and a.apply _ and similarly for b. I included three explicit calls in the form of a.apply _, b.apply _ and a.apply(10). Clicking on def apply does indeed show the list of these three usages. That it is not able to figure out that a(2) is an apply call is a bug, in my opinion.

Comments