Example:
object Test {
def main(args: Array[String]): Unit = {
Test().usedMethod()
}
}
case class Test() {
private def usedMethod(): Unit = {
}
}
Sonarqube 8.4.2.36762 reports: Remove this unused private "usedMethod" method
Example:
object Test {
def main(args: Array[String]): Unit = {
Test().usedMethod()
}
}
case class Test() {
private def usedMethod(): Unit = {
}
}
Sonarqube 8.4.2.36762 reports: Remove this unused private "usedMethod" method
Hello @pieter12321,
usedMethod()
is only used by the test code, and therefore unused in the production code, which is the purpose of the “unused private methods” rule.Olivier
Hello,
Sorry about that, I thought the scala
tag would be enough :). I guess you are inferring this is test code by the name Test
, but this is just the name of the class, you could substitute any other name.
Thanks for the clarification. I missed the scala tag and indeed I don’t know Scala enough (I don’t know Scala at all is a better statement) to assess that the Test
class was not necessarily a test class.
I could reproduce your “problem” (issue raised on “unused private method”). However I am not sure this is really a false positive. I am reaching my limits of comprehension of the Scala language: It seems from the language that a private
method within a class
should make the method only accessible from within that class. This does not seem to be the case of a case class
like in your code sample. I did not find clear documentation on case class
that would explain if and how private elements of the class can be accessed from the outside.
Could you clarify that ?
Thanks.
Certainly I can clarify: this is a special case in the scala language where a class (case class Test
) can have a so-called companion object (object Test
): https://docs.scala-lang.org/overviews/scala-book/companion-objects.html
If you’re familiar with Java, a useful analogy is that the declarations in a companion object are much like static declarations in the corresponding class, something like (java):
class Test {
static void main(String[] args);
private void usedMethod();
}
Thanks, that clarifies and that sounds like a false positive at first sight then.
But I really need to discuss with our Scala experts before coming back with a final statement on this.
We’ll keep you posted.
Thanks for this good catch. This is a false positive.
I’ve created a ticket, to fix it. Here you can find the link https://jira.sonarsource.com/browse/SONARSLANG-500
Have a nice day!
This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.