简体   繁体   中英

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?

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>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM