简体   繁体   中英

Error converting Optional<String> to Integer from TextInputDialog

In this example I have tempSocket1 and tempSocket2 but I really just want one of them. I just included both to show I tried both methods, but I keep getting an error, "the method valueOf(String) in the type Integer is not applicable for the arguments (Optional)." I thought both of these methods were the ones used for converting a string data type to integer, but I'm not sure how the Optional part changes the whole system.

private void showTextInputDialog() {
        TextInputDialog changePort = new TextInputDialog("Settings");
        changePort.setHeaderText("Change Port");
        changePort.setContentText("Please enter port number to be used for establishing connection...");

        Optional<String> result = changePort.showAndWait();
        result.ifPresent(e -> {
            Integer tempSocket1 = Integer.valueOf(result);
            Integer tempSocket2 = Integer.parseInt(result);
            }
        );
}

To convert an Optional to an Integer, it is necessary to invoke the get() method before the conversion.

Optional<String> cadena = Optional.of("333");
Integer num = Integer.valueOf(cadena.get());

You see, Integer.valueOf and Integer.parseInt methods need an argument of type String , but you are passing an Optional<String> . So that's why the error occurred. Optional string and string are not the same.

Just think about this, if Optional<String> were the same as String , would ArrayList<String> be the same as String ? Would LinkedList<String> be the same as String ? What about HashMap<String, Integer> ? Would it be both a String and an Integer ?

The chaos that treating generic types the same as their generic type arguments would bring is destructive! Imagine calling charAt on an optional string! Without the implementation, no one knows what will happen...

So yeah, never think that generic types are the same types as the generic type parameters.

You're trying to pass an Optional<String> instead of a normal String . You need to fetch the string first with .get() before converting your result to an integer. Or use result.ifPresent(e ...) that will automatically unwrap the optional value and convert it to an Integer.

Optional<String> result = changePort.showAndWait();
result.ifPresent(e -> {
    Integer tempSocket1 = Integer.valueOf(e);
    Integer tempSocket2 = Integer.parseInt(e);
    }
);

Just to extend other answers it may looks better using map method, and even more with lambda and method reference:

Optional<String> result = changePort.showAndWait();
Integer tempSocket = result.map(Integer::valueOf).orElse(8080);

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