Self-Motivated Wu
Self-Motivated Wu

Reputation: 407

How to judge wheather a value exists in scala?

I am new to scala. I try to debug a scala project by idea, So I need to set a conditional breakpoint. However, I found a situation that two subclasses inherits the same trait "Handle", so the two subclasses can be used to as input to a function judge. But, class B has a value name, class C does not have this variable. I want to know, how to judge the input of function "final" has variable "name".

trait Handle {

}

abstract class F {
  val name: String
}
class B extends F with Handle {
  val name = "..."
}

class C extends Handle {
  val h = "..."
}
def final(h:Handle) = {...}

Upvotes: 0

Views: 33

Answers (1)

Mateusz Kubuszok
Mateusz Kubuszok

Reputation: 27595

Since Handle is not sealed you cannot enumerate a finite list of all possible implementations. At best you could:

def final(h: Handle) = h match {
  case b: B => // h is B, so from now we can access B's method with b
  case c: C => // h is C, so from now we can access C's method with c
  case _    => // h is some other implementation of Handle
}

If Handle was sealed you could do:

def final(h: Handle) = h match {
  case b: B => // h is B, so from now we can access B's method with b
  case c: C => // h is C, so from now we can access C's method with c
  // compiler can prove that no other implementation than these two is
  // possible, so you don't have to consider it with a wildcard match
}

Once you match h against something you have detailed knowledge what you can do with it.

Upvotes: 1

Related Questions