Dan Dan - 16 days ago 7
Scala Question

Scala parameter value does not compare correctly - checking for empty string value with if statement in view

I have a view using Scala:

@(user: User = null, scripts: Html = Html(""), isLoggedIn: String = "", currentEmail: String=controllers.helpers.AccessMiddleware.getSessionEmail())(content: Html)


The currentEmail string is what I am interested in. It is empty or "" when a user is not logged into the system and contains an email value when logged in.

I can see that the value is empty or "" when opening the URL/application, but the if statement inside the view continually goes to the else part of the statement, display an empty string and not "Login":

<nav class="navmenu center">
<ul>
<li class="scroll_btn"><a href="/">Home</a></li>
<li class="scroll_btn"><a href="/signup">Register</a></li>
<li class="scroll_btn"><a href="/admin">Admin</a></li>
@if(currentEmail == "") {
<li class="scroll_btn"><a href="/auth">Login</a></li>
} else {
<li class="scroll_btn"><a href="/useraccount?email=@currentEmail">@currentEmail</a></li>
<li class="scroll_btn"><a href="/logout">Logout</a></li>
}
</ul>
</nav>


It always determines that there is a value even though it is empty. Here is the page source:

<nav class="navmenu center">
<ul>
<li class="scroll_btn"><a href="/">Home</a></li>
<li class="scroll_btn"><a href="/signup">Register</a></li>
<li class="scroll_btn"><a href="/admin">Admin</a></li>

<li class="scroll_btn"><a href="/useraccount?email="></a></li>
<li class="scroll_btn"><a href="/logout">Logout</a></li>

</ul>




Is there another way to compare to an empty string? Also, how do you make the currentEmail value lower case? .toLowerCase() does not work...

I appreciate the help!

Answer

Use Option

Option with forall will handle the case where currentEmail is null

Option(currentEmail).forall(_.isEmpty)

Your code becomes

@if(Option(currentEmail).forall(_.isEmpty)) {
  <li class="scroll_btn"><a href="/auth">Login</a></li>
} else {                                        
  <li class="scroll_btn"><a href="/useraccount?email=@currentEmail">@currentEmail</a></li>
  <li class="scroll_btn"><a href="/logout">Logout</a></li>
}