This is a trivial question, I was just wondering if I can use something Scala-ish here. I have 2 different classes (Server1 and Server2) both implement a common interface/trait (with methods .A() and .B()).
This obviously confuses the compiler:
var server = null
if(cond) server=new Server1 else server=new Server2
server.A() //or server.B()
I was mainly curious if I could use Scala’s Option to get around this in a neat way. Thanks.
Type annotations can always be added:
However, since vars are somewhat icky…
In the second example, Scala should be able to unify types. (I am fairly certain there are some situations it can’t unify — or where it doesn’t unify quite as desired, but give it a shot before falling back to type annotations, which can be added as per the first example.)
REPL demonstration:
Happy coding.
Structural typing example, the
typealias is for convenience but technically not required.Note that the type annotation was required, otherwise…