Get current user role in drupal 8 or 9

Getting the current user role in code is quite easy, here's the snippet.

$roles = \Drupal::currentUser()->getRoles();

if(in_array('editor', $roles)) {
  // Do something if user has role editor
}