The NVL() function for Java and Ruby

Anyone who used PLSQL is already familiar with the NVL(foo, bar) function..

This feature lets us set a default value if the first is null.

But if you want something like that in Ruby and Java? :>

Ruby

In Ruby this trick is easy, you don’t even need a function, just:

foo ||= bar

If the “foo” variable is nil, than “foo” will be set to “bar”. Else, “foo” will mantain his value.

Java

In Java is not that simple.

Since Java needs the objects to be strongly typed, you send the object type dynamically, so it will assurance that the objects are from the same type:

public <T> T nvl(T arg0, T arg1) {
	return (arg0 == null)?arg1:arg0;
}

Done.

Advertisements
Tagged , , , ,

One thought on “The NVL() function for Java and Ruby

  1. mike says:

    how would you use this in actual code then?

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: