How to use ternary operator with new?

2019-09-25 01:34发布

I have this code:

if (providers.length > 0) 
        this.providers = providers;
    else 
        throw new IllegalArgumentException();

And i want to simplify it. I went for:

(providers.length > 0) ? this.providers = providers : throw new IllegalArgumentException();

But that gives me a compiler error. Why?

标签: java ternary
4条回答
小情绪 Triste *
2楼-- · 2019-09-25 01:46

You could do that too:

this.providers = providers.length > 0 ? providers : null;
if (this.providers == null)
    throw new IllegalArgumentException();

But normally You should let Your code in cases like that as it is. That's in that case much better and less complicated.

查看更多
做个烂人
3楼-- · 2019-09-25 01:55

Method Call using Ternary Operator

It's the same thing for Java, you have to return the same type of object.

查看更多
Animai°情兽
4楼-- · 2019-09-25 01:59

The reason why the ternary operator doesn't work is because that is for assigning values. Meaning: the "else" part after ":" needs to return a value of the same type as the "then" case after "?".

And throw new doesn't return a providers object ...

But in the end, that doesn't matter anyway; as the really simple version of that code looks more like:

if (providers.length == 0) {
    throw new IllegalArgumentException();
}

this.providers = providers;

And in order to make things easier to read, you could even go for:

checkProvidersNotEmpty(providers);
this.providers = providers;

In other words: you move the exception throwing into a separate method. The implicit convention here would be that a method named checkSomething() throws an exception when the check it does fails. And beyond that: give a reasonable message when creating that exception. It will help debugging later on.

You do not strive for the shortest program possible, but for the shortest version that comes with the best reading experience.

Using the ternary operator here would not result in an "easy to read" experience. Thus: forget about it.

查看更多
一夜七次
5楼-- · 2019-09-25 01:59

I don't think you can actually do this because the statement throw new IllegalArgumentException() cannot be assigned to providers.

From Java documentation about Equality, Relational, and Conditional Operators :

The Conditional Operators

[...] Another conditional operator is ?:, which can be thought of as shorthand for an if-then-else statement (discussed in the Control Flow Statements section of this lesson). This operator is also known as the ternary operator because it uses three operands. In the following example, this operator should be read as: "If someCondition is true, assign the value of value1 to result. Otherwise, assign the value of value2 to result."

查看更多
登录 后发表回答