7 Jul 2004 15:42
Re: using || and && in a more clever way
On 7 Jul 2004, at 14:36, John Wilson wrote: > On 7 Jul 2004, at 13:47, jastrachan@... wrote: >> John Rose made heaps of good suggestions during a face to face at >> JavaOne. I'll try brain dump them to the mail lists and/or wiki over >> the coming weeks. This one's particularly cute. >> >> x = a || b >> >> would return either the value of a, if its coerced to a boolean and >> is true or the value of b. Right now null is false and non null is >> true. So if a or b could be null you could use the above to return >> the non null value. >> >> A common requirement is if a value is null then use another value. So >> we could do >> >> text = customer.name || "unknown" >> >> to grab some text and if its null use some default value. >> >> Similarly if we want to set a variable if its null we could replace >> code like this >> >> if (x == null) { >> x = "foo" >> } >> >> with >> >> x ||= "foo" >> >> >> We could do similar things for && and &&= as well. >> Thoughts? >> > > x = false > > x ||= "foo" > > sets x to 'foo" doesn't it? Yes > so it's not actually equivalent to > > if (x == null) { > x = "foo" > } So in the above its equivalent to if (!x) { x = "foo" } > I'm not completely convinced that treating null as false and non null > as true will lead to non surprising results (sorry about the quadruple > negative!!) Can you think of any? > I like the functionality it offers; I'm less keen on overloading "||". It really is just using existing || - the only real difference is that the result of the || expression is the value of one of the 2 expressions as their original types rather than coerced to a boolean. So its only a minor change to how things work right now. James ------- http://radio.weblogs.com/0112098/
RSS Feed