I wrote a function in my service class where I evaluate a passed parameters from controller but Grails is returning wrong evaluation results.
def list(String q,String qval,String srt,String ord){
log.debug("q==="+q)
log.debug("qval==="+qval)
log.debug("srt==="+srt)
log.debug("order==="+ord)
all these debug statements print null as expected. Now
boolean qvalbool=qval?.trim()
log.debug("qvalbool===>>"+qvalbool) prints true!!!
!StringUtils.isEmpty(q) && !StringUtils.isEmpty(qval) returns true!!
both statements should return false while they are returning true what is going on with this? any ideas?
I'm using grails 2.4.2
Evan Wong's comment is very likely correct that you're seeing a string containing the word null.
Often when Groovy prints out values it's not apparent what their type is.
groovy:000> null
===> null
groovy:000> 'null'
===> null
Also in Groovy the expression null + '' evaluates to the String 'null'.
That would be an easy way to change the value of this parameter so it contains the string 'null'.
Related
Can someone simply explain to me how null assertion (!) works and when to use it?
The ! operator can be used after any expression, e!.
That evaluates the expression e to value v, then checks whether v is the null value. If it is null, an error is thrown. If not, then e! also evaluates to v.
The static type of an expression e! is (basically) the static type of e with any trailing ?s remove. So, if e has type int?, the type of e! is int.
You should not use e! unless e can be null (the type of e is potentially nullable).
The ! operator is dynamically checked. It can throw at runtime, and there is no static check which can guarantee that it won't. It's like using a value with type dynamic in that all the responsibility of preventing it from throwing is on the author, the compiler can't help you, and you need good tests to ensure that it won't throw when it's not supposed to.
It's called an assertion because it should never throw in production code.
So, use e! when you know (for some reason not obvious to the compiler, perhaps because of some invariant guaranteeing that the value is not null while something else is true) that e is not null.
Example:
abstract class Box<T extends Object> {
bool hasValue;
T? get value;
}
...
Box<int> box = ...;
if (box.hasValue) {
var value = box.value!;
... use value ...
}
If you are repeatedly using ! on the same expression, do consider whether it's more efficient to read it into a local variable just once.
Also, if (like this Box example) the value being null is equivalent to the other test you just did, maybe just check that directly:
Box<int> box = ...;
var value = box.value;
if (value != null) {
... use value ...
}
This code, with an explicit != null check on a local variable, is statically guaranteed to not throw because the value is null.
The code using ! above relies on the author to maintain whichever invariant allowed them to write the !, and if something changes, the code might just start throwing at runtime. You can't tell whether it's safe just by looking at the code locally.
Use ! sparingly, just like the dynamic type and late declarations, because they're ways to side-step the compiler's static checking and ensure it that "this is going to be fine". That's a great feature when you need it, but it's a risk if you use it unnecessarily.
Dart null safety says that by default all variables of primitive data types (int, String, bool) are non-nullable, they can't have a null value, right? Let suppose if I have a variable 'a' of type int then I can't assign it a null value unless to use question mark with data type.
int a=null;
the above code will generate an error like 'The value 'null' can't be assigned to a variable of type 'int' because 'int' is not nullable.'
But at the same time, dart says that all initialized variables have a default value of null. My question is why statement-1 doesn't match with statement-2? Dart should not allow us to declare an uninitialzed variables because uninitialzed variables contain null value which doesn't apply with its own statement. Can anybody clear my confusion?
if you declare variables like this
int? a = null;
int? a;
Both will be null;
when you put '?' after variable you are saying to dart "hey I'm okay if it's null or not"
but sometimes you won't execute some function if the variable passing to it is null so you have to declare a variable without '?' in this case you are saying to dart "hey this variable must not be null";
also, you have to do research about null checkers, because it's very important
The ?, !, ?? null checkers
I'll keep it very simple
? says It's ok if the value is null
! says it must have non null value
?? says if it's null then assign another value...
String? nullableValue;
String nonNullableValue;
nonNullableValue = nullableValue; //throws error because nullable value cants be assigned to non nullable variable;
nonNullableValue = nullableValue ?? "undefined or null"// You are saying to dart "hey if nullable value null then assign "undefined or null";
nonNullableValue = nullableValue! // You are saying to dart "Hey this value Must not be null . But you have to check value for null with if condition like this
if(nullableValue !=null) {
nonNullableValue = nullableValue!;// By putting ! you are saying "don't worry dart this is checked value and its 100% not null";
}
The main reason for null safety is checking or preventing a variable to be null
Please read official docs for more information
Inside a controller i just test these two lines. RaceRegistration domain has a property compositeEvent. So, i access the Registration domain first and then access the compositeevent using .compositeEvent.
println (RaceRegistration.get(r.toLong()))
println (RaceRegistration.get(r.toLong())).compositeEvent
The following error is thrown. As you can see the first print succeeds i.e it gets the Registration domain but the second println fails. My question is why is it throwing null pointer when we are certain that the RaceRegistration domain was accessed successfully.
com.runnercard.registration.RaceRegistration : 8
ERROR errors.GrailsExceptionResolver: NullPointerException occurred when processing request: [POST] /roadrace/message/sendEmail - parameters:
I appreciate any help. Thanks!
Null is null. Don't doubt this: it is true.
The 'void' println expression evaluates to null and the failing code is roughly equivalent to the following:
x = println (RaceRegistration.get(r.toLong()))
// x is null - so the following results in a NullPointerException
x.compositeEvent
It is probable that the parenthesis is merely in the wrong spot (or even over-specified):
println (RaceRegistration.get(r.toLong()).compositeEvent)
// -or
println RaceRegistration.get(r.toLong()).compositeEvent
I'm using VB.NET MVC 5.1 in VS2013 using Razor
siq.Price is a Decimal?
I'm trying to check if siq.Price has a value, and if so print it as a currency. I recieve this error when trying to access the .Value property for elements where true they returned true for .HasValue:
Nullable object must have a value.
Description: An unhandled exception occurred during the execution of the current web request.
Please review the stack trace for more information about the error and
where it originated in the code.
Exception Details: System.InvalidOperationException: Nullable object
must have a value.
I tried both of these lines of code, believing they should work without issue, yet recieved the error above:
#IIf(siq.Price.HasValue, siq.Price.Value, "N/A")
'and
#IIf(siq.Price.HasValue, siq.Price.Value.ToString("C"), "N/A")
As soon as I remove the .Value from the TruePart then it started working:
#IIf(siq.Price.HasValue, siq.Price, "N/A")
'and
#IIf(siq.Price.HasValue, String.Format("{0:C}", siq.Price), "N/A")
Can anyone explain why this is happening?! I'm rather perplexed.
NOTE: This piece of code works on it's own if the Price has a value, but not in the IIf():
#siq.Price.Value.ToString("C")
The IIF() function in VB.Net always evaluates both the true and false parts. Instead, you should change to use the IF() operator, which only evaluates the return value, so something like:
#If(siq.Price.HasValue, siq.Price.Value.ToString("C"), "N/A")
At first glance, VB.NET's IIf method seems equivalent to C#'s ternary operator (?:), but there's a big difference: because it's a method, not an operator, there's no short circuiting, and both parameters are always evaluated before being passed to the method.
What this means is that regardless of whether HasValue is true, both siq.Price.Value and "N/A" are evaluated, leading to the exception you saw.
IIf() runs both the true and false code. VB's conditional If operator is short-circuit so you can now safely write the following,
which is not possible using the IIf function:
Dim len = If(text Is Nothing, 0, text.Length)
I have the following combobox:
<g:select name="ticketType" from="${app.domain.enums.TicketType?.values()}"
keys="${app.domain.enums.TicketType.values() }"
value="${ticketInstance?.ticketType}"
noSelection="${['null': 'Select One...']}"
/>
I've setup the following constraint for ticketType in command object
ticketType nullable: true, blank:true
TicketType is a very simple enum:
public enum TicketType {
QUESTION, SUPPORT, MAINTENANCE, NEW_FUNCTIONALITY, MALFUNCTION
}
And every time I don't setup some value for ticketType in my GSP I get the following error:
Failed to convert property value of type 'java.lang.String' to required type 'com.coming.enums.TicketPriority'
It's like in case of no selection g:select sets the value for "null" (string).
What am I missing?
Rather than using the 'null' literal, have you tried using an empty string as your noSelection attribute? e.g. noSelection="${['':'Select One...']}"? This may do a proper conversion to a true null value during data binding.
As your error says - you do have a string in your noSelection. This can't be converted to any of your enum values.
Remove the quotation marks of your null and it should work (it works for me with grails 2.0):
<g:select name="ticketType" from="${app.domain.enums.TicketType?.values()}"
keys="${app.domain.enums.TicketType.values() }"
value="${ticketInstance?.ticketType}"
noSelection="${[null: 'Select One...']}"/>
Under Rails 3.3.x, no variation of providing the "null" value worked. In the end, I resolved it by adding this line in to the controller+action before doing any use of the params:
// convert "null" strings to REAL nulls
params.account.each { it.value = (it.value == 'null' ? null : it.value) }
After that, the following worked fine:
account.properties = params.account