0

This will compile

 public ResponseEntity<User> getUserById(@PathVariable(value = "id") Long userId) throws UserNotFoundException {
        ResponseEntity u = userRepository.findById(userId)
                .map(p->ResponseEntity.ok(new UserResource(p)))
                .orElseThrow(() -> new UserNotFoundException(userId));
        return u;
    }

But this won't

 public ResponseEntity<User> getUserById(@PathVariable(value = "id") Long userId) throws UserNotFoundException {
        return userRepository.findById(userId)
                .map(p->ResponseEntity.ok(new UserResource(p)))
                .orElseThrow(() -> new UserNotFoundException(userId));
    }

How come?

erotsppa
  • 14,248
  • 33
  • 123
  • 181
  • See: [What is a raw type and why shouldn't we use it?](https://stackoverflow.com/questions/2770321/what-is-a-raw-type-and-why-shouldnt-we-use-it) – Jesper Nov 05 '19 at 08:40

1 Answers1

3

The first code snippet returns instance of ResponseEntity<UserResource> which is then assigned to a raw type variable. Then the raw type variable is returned to a variable of generic type (which should produce a warning). It will throw an exception in runtime if any code reaches fields of ResponseEntity of the wrong type. So the first code compiles because compiler allows assigning raw type variables to generic and vice versa.

The second code snippet doesn't use raw types, so the generic type compatibility check is done (as usually at compile time since the generic types don't exist in runtime due to erasure) - thus it correctly fails to compile.

leokom
  • 1,862
  • 1
  • 15
  • 26