Hi all,
i’m trying to reproduce the collapsed “if” loops in Scala.
This is what I mean:
Collapsed “if” loop, at least as I’m tryng to reproduce the Java one:
val length : Int = 1;
val s : String = “s”;
return (length == s.length()) ? length : (length + 1);
But, using scala I get this error:
error: identifier expected but integer literal found.
return (length == s.length()) ? length : (length + 1);
So, please whch is the correct syntax of the collapsed “if” loop in scala?
Thank you.
pengyh
2
scala has no “? :” statement IMO.
you will use the if (…) else (…) syntax instead.
2 Likes
You also appear to be doing a while loop here.
return if (length == s.length()) length else length + 1
1 Like
On latest Scala,
scala> def f: Any = return (length == s.length()) ? length : (length + 1)
^
error: not found: type +
^
error: value ? is not a member of Boolean
because it parses as
def f: Any = return (length.$eq$eq(s.length()).$qmark(length): $plus[length, 1.type])
You do not need the return. You can let the code evaluate the expressions.
1 Like