问题
I have the following code trying to use the Optional class:
import java.util.Optional;
// one class needs to have a main() method
public class HelloWorld
{
public String orelesMethod() {
return "hello";
}
public void test() {
String value;
value = Optional.ofNullable(null).orElse(orelesMethod());
System.out.println(value);
}
// arguments are passed using the text field below this editor
public static void main(String[] args)
{
HelloWorld hello = new HelloWorld();
hello.test();
}
}
when compiling it, it says:
incompatible types: Object cannot be converted to String
value = Optional.ofNullable(null).orElse(orelesMethod());
I can not find it out what is the problem, can anyone help on it?
Thank you!
回答1:
You have defined value
to be of type String
, but Optional.ofNullable(null)
returns Optional<Object>
because any object type can be null
and you did not specify the actual type. Then you are calling orElse
on the object of type Optional<Object>
and because T
is Object
, the orElse
method returns an object of type Object
which cannot be converted to String
.
Therefore you need to specify the type while calling ofNullable
:
value = Optional.<String>ofNullable(null).orElse(orelesMethod());
You might also want to use orElseGet
method in order not to call orelesMethod
when the optional contains value.
回答2:
A String is an Object, but an Object is not necessarily a String and thus this error. Try this :
public String orelesMethod() {
return "hello";
}
public void test() {
Object value;
value = Optional.ofNullable(null).orElse(orelesMethod());
System.out.println(value);
}
回答3:
Optional<T>
is the new (since Java 8) way of handling values which might be null
.
You get the value by calling .get()
.
Note that calling .get()
without the value being set throws an NoSuchElementException.
See the reference: Class Optional
Edit:
Also, the return value of your orElse()
will be of the same time you initialized you class with. Since that's not a String but null
you don't get a String as return.
来源:https://stackoverflow.com/questions/51931835/object-cannot-be-converted-to-string-when-using-optional-class-in-java