0

I have this piece of code:

 if (service.isHostel) {
            return new Hostel({url: service.url});
        } else {
            return new booking({url: service.url});
        }

that I want to express in 1 line,

service.isHostel ? Hostel({url: service.url}) : return new booking({url: service.url})

but I have a compilation error:

Expression expected.

3
  • 2
    Try return service.isHostel ? new Hostel({url: service.url}) : new booking({url: service.url}) Commented Feb 3, 2020 at 8:14
  • are you missing the new key word near the hostel object ? Commented Feb 3, 2020 at 8:15
  • the whole code should be return return service.isHostel ? new Hostel({ url: service.url }) : new booking({ url: service.url }); Commented Feb 3, 2020 at 8:16

2 Answers 2

2

You can only write expressions(piece of code which returns are value) inside ternary operation. return is a statement which can't be used inside the expression of ternary operators.

Here you have to return both the values you can use return before ternary

return service.isHostel ? new Hostel({url: service.url}) : new booking({url: service.url})
Sign up to request clarification or add additional context in comments.

Comments

2

You need to add a new operator as well for Hostel and omit the return return statement inside of the ternary.

return service.isHostel ? new Hostel({url: service.url}) : new booking({url: service.url});

Another version is to choose different classes.

return new (service.isHostel ? Hostel : booking)({url: service.url});

1 Comment

I like this method because if you move (service.isHostel ? Hostel : booking) to a seperate function, you arrive at the factory pattern

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.