In Java, can I use a conditional expression to select link types?

Can I use a conditional expression to select the type of link as shown below?

??? = isTrue() ? Integer : Double;

Is there something I can put in " ???" to make a piece of code compile?

Change . When I wrote Integer and Double, I did not mean an instance of Integer or Double. I meant the reference type Integer and Double.

+3
source share
7 answers

I think you are trying to use the ternary logical operator to select the reference type of your variable.

Java, Java - , . , .

+4

, - ;

Number n = isTrue() ? 1 : 1.0;

, - , .

EDIT:

​​Java, , , :

CharSequence cs = isTrue() ? "I'm a String"
                           : new StringBuilder().append("I'm a StringBuilder");

System.out.println(cs+" "+cs.getClass());
// prints out
// I'm a String class java.lang.String
+4

, Java. Integer Integer.class Double by Double.class, . , , .

,???

Class var
+4

- , Integer Double , , , , . , , , .

+1

: , ... Jesper , , if/else , :

 Number n;
    if (isTrue()) { n = Double.valueOf(1.0); }
    else {n = Integer.valueOf(1);}
    System.out.println(n.getClass().getName()) //prints java.lang.Integer if isTrue returns false

:

Double Integer, . .

Number n = isTrue() ? whateverYouDoToReturnInteger() :  whateverYouDoToReturnDouble();

, , , .

0

, . , - , .

, ( ):

Number n = functionReturningBoolean() ? 1.0 : 1;

... , , , . , , ( , , !)

0
source

If you are just trying to select a type, not an instance, you can do something like:

Class result = isTrue ()? Integer.class | Double.class;

0
source

Source: https://habr.com/ru/post/1788707/


All Articles