When a Dog is Not Always an Animal…

When a Dog is Not Always an Animal…

This dog obviously doesn’t seems to agree with the title, but looks like the Kotlin compiler might have a different idea about this! Below is a very small experiment using the Spring Reactive Flux api from Project Reactor (version 3.1.7) to illustrate how sometimes a dog is not always an animal:

It seems like directly returning the result of the expression Flux.just(Dog()) validates the self-esteem of the dog that it is indeed also an animal, but when instead we declare a variable to hold the result of that exact same expression, trying to return that value would directly send the dog to the dog psychologist with a serious identity crisis…

A crisis that is somewhat manageable when treating a single dog or a group of dogs sequentially, but when dealing with a group of dogs, it’s a bit more complicated if we want to take care of each dog in parallel:

Unless you only want to take care of dogs and no other type of animals:

So if we want to take care of a group of dogs and do so in parallel, make sure to treat them specifically as dogs and not like simple animals… which for me is not a satisfying conclusion obviously, self-doubt is kicking here, so some additional research and a bit of help from all of you would most probably lead to a better explanation of what is going on here.

Of course there is the concept of covariance in both Java and Kotlin generics, in particular there is the concept of use-site variance (or type projections) that would restore sanity in our dog’s mind:

But it’s still interesting to see that we don’t need it when we are directly returning the result of the expression without declaring a variable first…

Leave a Reply

Your email address will not be published.

%d bloggers like this: