简体   繁体   中英

Can't return value directly from method in Java, why?

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?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM