Conditionally add "optional items" with array initialization syntax?
Asked Answered
M

5

7

I'm wondering if I can easily have an if statement somehow here:

public Object[] tableItemFromVisit(Visit visit, boolean editable) {
    return new Object[] {
            visit.getIdVisit(),
            visit.getProfession().getProfessionName(),
            visit.getSpiProfessional().getFullName(),
            RegularFunctions.getTimeFormat().format(visit.getVisitDate()),
            RegularFunctions.toNormalCapitalizedText(visit.getVisitState()
                    .toString()), visit.getReason(), 
            if (editable) { "Edit" }, 
            };
}

How is this structure even called? An array specification or what? Anyway if the variable "editable" is true, it has to have an "Edit" string, if it's false, it doesn't need anything... Obviously I don't want to write two return statements that are way too similar to each other...

Mournful answered 9/1, 2013 at 7:1 Comment(3)
if is a statement and cannot be used as an Expression. ?: is an expression: of course, all expression must evaluate to a value.Andes
The title should be improved, but I don't know how.Billingsgate
@MiserableVariable Yeah, I know, sorry, I couldn't think of a good title myself...Mournful
J
3

Construct the above array as an ArrayList and return its toArray?

Essence of the idea is to do something like this.

ArrayList<Object> ret = new ArrayList<Object>(new Object[] {
            visit.getIdVisit(),
            visit.getProfession().getProfessionName(),
            visit.getSpiProfessional().getFullName(),
            RegularFunctions.getTimeFormat().format(visit.getVisitDate()),
            RegularFunctions.toNormalCapitalizedText(visit.getVisitState()
                    .toString()), visit.getReason()
            // don't add Edit item at all yet
            })

if(editable)
     ret.add("Edit");

return ret.toArray();

I am not sure if this kind of initialization works though, if not Arrays.toList can also be used, or just add one by one.

Jeminah answered 9/1, 2013 at 7:8 Comment(7)
@MiserableVariable: I disagree. It is clear simple and readable. Unless there is a very good reason why NOT to use it (i.e. performance is critical in this section), there is no reason why not to.Dialectology
@MiserableVariable In some other languages, yes (like Scala, C#, Ruby, etc :D). However, Java's mediocre Collection syntax/support is showing here .. of course, I would argue why not just return a List?Andes
To each his own :) I did not think it pretty, that is why I wrote there is no good alternative.Billingsgate
Can you show what it would look like, cause I don't know what you mean by this? I'm not sure if I could return a List, since the new Object[] was used in the example, I'm using this for table items in Vaadin frameworkMournful
Looks really good, I'm trying this out right now, but there seems to be something wrong with the type arguments or something: ArrayList<Object> ret = new ArrayList<>( it says cannot infer type arguments for ArrayList<> and '<>' operator not allowed for source level below 1.7 (I'm using 1.6 for my project)Mournful
@ArturasM you can use ArrayList<Object>Jeminah
@KarthikT Thanks. Well I couldn't get it to work by initialising Object[] {...} in constructor, had to use normal ArrayList and just add items to it and use the toArray method in the end. Works like charm and the code looks nicely readable, there are no unnecessary repetitions.Mournful
B
2

Passing extra parameter using the construct provided is not possible. You modify your code in one of following ways:

Try ternary operator:

editable ? "Edit" : ""

OR

editable ? "Edit" : null

if(editable)
{
    return new Object[] {
        visit.getIdVisit(),
        visit.getProfession().getProfessionName(),
        visit.getSpiProfessional().getFullName(),
        RegularFunctions.getTimeFormat().format(visit.getVisitDate()),
        RegularFunctions.toNormalCapitalizedText(visit.getVisitState()
                .toString()), visit.getReason(), 
        "Edit" }
}
else
{
return new Object[] {
        visit.getIdVisit(),
        visit.getProfession().getProfessionName(),
        visit.getSpiProfessional().getFullName(),
        RegularFunctions.getTimeFormat().format(visit.getVisitDate()),
        RegularFunctions.toNormalCapitalizedText(visit.getVisitState()
                .toString()), visit.getReason(), 
        }
}
Bostow answered 9/1, 2013 at 7:4 Comment(8)
NO! It does not have the same affect, it has an extra element in the array with value "" or null if the condition does not hold.Dialectology
But then an extra member will be created which will be an empty string, I need no object there? Or do I misunderstand it?Mournful
@ArturasM: Do you want to add extra parameter based on editable state? if yes, not possible in this construct.Bostow
whoa easy with the downvotes, the question is somewhat ambiguous -- need nothing can be considered to be null is okBillingsgate
@Bostow exactly, I want nothing if it's false. Is there some construct I can use to achieve that?Mournful
i dont understand why this answer was downvoted, his code example answers the question..Bewhiskered
That's a little ugly. is it maybe possible to create that object array variable and then create another object array variable with an extra element if "editable" is true? But arrays are probably not flexible enough for that? I'd have to use a for loop to achieve it, right?Mournful
@AnanthaSharma he had the completely wrong answer first, the part after the ruler line is added later.Billingsgate
B
1

If I understand you right, you want the returned Object[] to have and extra element if editable is true.

That is not possible in java.

If null can be used there, you can use editable ? "Edit" : null in place of if (editable) { "Edit" } , but you probably already know that.

Billingsgate answered 9/1, 2013 at 7:3 Comment(1)
So the only way would be to write the if before and write to return statements which differ in one last element either present or not?Mournful
S
0

It looks like you want to use conditional operator like this:

editable ? "Edit" : "" (or null if you want it that way).

Obviously, it has the extra element.

Socio answered 9/1, 2013 at 7:6 Comment(2)
NO! It does not have the same affect, it has an extra element in the array with value "" or null if the condition does not hold.Dialectology
Nope, it's more like it either has an element or doesn't have an element at all if the condition is falseMournful
N
0

Let's assume that you are trying to make an object to contain data about visits. Why don't you want to create a function for if (editable) { "Edit" } and utilize encapsulation?

private String getEditFeedback(boolean editable){
  if(editable){
   return "Edit";
  } else {
   return //something
  }
}

Then inside your code,

 public Object[] tableItemFromVisit(Visit visit, boolean editable) {
        return new Object[] {
                visit.getIdVisit(),
                visit.getProfession().getProfessionName(),
                visit.getSpiProfessional().getFullName(),
                RegularFunctions.getTimeFormat().format(visit.getVisitDate()),
                RegularFunctions.toNormalCapitalizedText(visit.getVisitState()
                        .toString()), visit.getReason(), 
               getEditFeedback(editable), 
                };
    }
Norther answered 9/1, 2013 at 7:13 Comment(1)
Very similar to the ternary operator issue - it will have an extra element in the array if the condition does not hold.Dialectology

© 2022 - 2024 — McMap. All rights reserved.