I have a class that contains code that I can tell from the logs is definitively being executed, but I cannot figure out where the method is being called. I am wondering, if a class has a get()
method defined, is it automatically called somehow, parhaps if other code in the class is executed? Is get()
magic?
I cannot share my actual code for privacy reasons. The following is complete BS code, but I hope it is enough for people to see what I'm talking about.
If I look for usages in my IDE of the A.get()
method, there are none. The only usage of the A.getHistory()
method is inside the A.get()
method. Finally, there are also usages of the A.extra()
method.
class A(count: Int) {
def get (date: LocalDateTime) : List[B] = {
getHistory(date, 0).get
}
def getHistory(date: LocalDateTime, tries: Int) : Try[List[B]] = Try({
val b : B = new B (date)
logger.info("method getHistory() is being called")
}) match {
case s: Success[List[B]] => s
case e: Failure[List[UnitChange]] =>
Thread.sleep(retryDelay)
getHistory(date, tries + 1)
}
def extra() = {
logger.info("method extra() is being called")
}
}
object C {
def run() {
A.extra()
}
}
If C.run()
calls A.extra()
, does A.get()
implicitly get called?
U: I have to support this code without being a real Scala developer. But I also need to know because I've been porting it to Java, and if methods are being magically called in Scala, that won't happen in Java, and I need to make some changes to make sure the magic code does get executed.
U: This is embarrassing, but it appears I diagnosed a zebra when it was a horse all the time. In other words ... it was a mistake on my part, the code in question was not getting called, and no magic is taking place.
I know of one example of a get()
call hidden inside of a pattern match. I rather doubt this is what you're seeing, but it's worth knowing about.
class MyClass(val arg: Int) {
def get: String = "what it takes"
def isEmpty: Boolean = false
}
object MyClass {
def unapply(mc: MyClass): MyClass = mc
}
new MyClass(42) match {
case MyClass(x) => s"got $x" //res0: String = got what it takes
case _ => "not"
}
The unapply()
gets called as part of the pattern match. unapply()
usually returns an Option
but it doesn't have to. Whatever it returns has to have an isEmpty
and a get
, both of which are called to complete the procedure.