Hacker News new | ask | show | jobs
by t1o5 3060 days ago
Curious why typecast if instanceof is checked already ? Wont the compiler know of this already ?

  if (view instanceof ChatMessageCell) {
  .......                    
   ChatMessageCell cell = (ChatMessageCell) view;
  ....
  }
4 comments

It's essentially just how Java works, and isn't that uncommon in statically typed procedural languages.

The `view` variable is still a reference of the parent type (Say `MessageCell` for now, can't be bothered to find that part in the code), and `MessageCell` references can only do certain things.

It's possible to check what the type of the underlying object is with `instanceof`, but that doesn't change the type of the reference.

If you want to do things that only a `ChatMessageCell` can do, you need to make a new reference of that type.

the java compiler does not do that unfortunately,

Kotlin would do what they call a 'smartcast' : ie if you did an instanceof if the if, in the corresponding {}closure you know the type of this object.

The whole code is probably unmaintanable for anybody other than it's original writer (and even for him, there must be a limit to how much code you can fit in your head).

I would love to work for Telegram, it is one of the products I use daily .. but if I had to handle this codebase, it would be a rare case of 'total rewrite or I am out'.

Incidentally, it looks like they are going to do this full rewrite. Telegram seems to have acqui-hired the creators of Telegram X and are prepping it up as a replacement.

I believe this is called “type narrowing”, and no, Java doesn’t have this.
It's Java, so no.