Is it possible to rewrite the following code (in t...
# announcements
s
Is it possible to rewrite the following code (in the screenshot) to be more compact The type of
e.entity
is "Entity". Many classes derive of this interface. But, I only want to do something with them if they're either Horse or Panda. And if they are, I want to do something general, for both panda and horse. And I want to also do something specific for them pandas and for horses I know It is possible to do the current construction, or copy the code which should be executed for both. But I was wondering if there was a more concise way to do this.
f
The only thing I see is to drop the inner
when
since you only have 2 possibilities and already checked that either is true. Hence, a
if (target is Panda) { /*panda specific*/ } else { /*horse specific */ }
will do.
j
By the time the outer when is done, your target has already been smart cast into what you need so you may be able to use extension functions. If you have an intersection (something that can be both a panda and a hourse) that needs separate handling, do that through FizzBuzz. If you have common logic, think about using Bridge Pattern.
f
An interesting solution would be through extension functions but Kotlin will fail claiming a receiver type mismatch due to missing support for union/intersection types.
s
This gets rid of at least one when
j
you can define a local function for hosepanda execution above the
while