U
U
user_of_toster2022-01-29 13:23:37
Java
user_of_toster, 2022-01-29 13:23:37

How to call a method on the result of expression?

This code works:

Long result = a.get(x) - a.get(b);
return result.intValue();

Why can't you call a method on the result of expression like this?
return (a.get(x) - a.get(b)).intValue();

Answer the question

In order to leave comments, you need to log in

1 answer(s)
M
Michael, 2022-01-29
@user_of_toster

Because Java has object types and primitive types. The expression appears a.get() - b.get()to be of type long, which is boxed into type Long during variable assignment. For type long, because it is a primitive type, there is no intValue() method, so it cannot be called. You can do this:

Long a = 1L;
Long b = 2L;
Integer c = Math.toIntExact(a + b);

Or switch to Kotlin in which there are no such problems and expressions can also call methods completely transparently.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question