When statement breaking early


Consider this piece of code

interface Foo
interface Bar

class Aclass: Foo, Bar

fun main(args: Array<String>) {
	val aclass = Aclass()
    when (aclass) {
        is Foo -> println("foo")
        is Bar -> println("bar")

I want it to print “foo” and “bar” because the class implements the two interfaces.
But it prints only “foo”.

I can chain ‘if’ statements, like “if (it is Foo) {…}” to make it work but is there a way to do it with a when statement ?


When clause by design uses only first condition which is satisfied (contrary to java/c switch). In most cases it is for the best, but in your case you should use old style separate ifs. It is probably for the best since you can clearly see that multiple branches are possible.


Ok thanks for the clarifications :slightly_smiling_face:, I’ll use ifs