Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I assign a variable from a method that might return null?

I have the following code where I assign the result of a Java method to a freemarker variable.

<#assign singleBenchmark = solverBenchmark.findSingleBenchmark(problemBenchmark)>

The problem is that return value of that Java method might null. And even though I check if that variable isn't null:

<#if !singleBenchmark??>
    <td></td>
<#else>
    <td>${singleBenchmark.score}</td>
</#if>

It still crashes on the <#assign ...> line if that Java method returns null, with this exception:

freemarker.core.InvalidReferenceException: Error on line 109, column 45 in index.html.ftl
solverBenchmark.findSingleBenchmark(problemBenchmark) is undefined.
It cannot be assigned to singleBenchmark
    at freemarker.core.Assignment.accept(Assignment.java:111)

How can I avoid this exception without having to call the findSingleBenchmark method multiple times in my ftl?

like image 960
Geoffrey De Smet Avatar asked Jul 22 '12 18:07

Geoffrey De Smet


1 Answers

The normal way to handle unsafe APIs like this is with the ! (bang) operator:

<#assign singleBenchmark = solverBenchmark.findSingleBenchmark(problemBenchmark)!>

This is detailed in this section of the FreeMarker docs and the reasoning is given here.


If your snippet is the actual code, you may shorten it (significantly) to:

<td>${singleBenchmark.score!""}</td>
like image 200
Dave Newton Avatar answered Oct 20 '22 11:10

Dave Newton