Reputation: 13
I want to compare fields of a JSONObject.
Here is the code I am trying:
x = JSONObject()
x.put("num",1)
if(x["num"] as Int < 2){
print("Good work!")
}
Error shown by IDE:
Type expected
Expecting a '>
Upvotes: 1
Views: 157
Reputation: 37680
The current code doesn't work as-is because the compiler sees Int<42
and thinks that you're trying to use a type parameter for the Int
type (like Int<T>
) which obviously doesn't work for 2 reasons:
Type expected
because 42 is not a typeExpecting a '>'
because well, there is no >
As @Alex.T said, you can disambiguate this by putting (..)
around the cast expression: (x["num"] as Int) < 2
.
However, if you're OK with your expression failing at runtime like this, you should instead use a typed getter like getInt():
val x = JSONObject()
x.put("num", 1)
if (x.getInt("num") < 2) {
print("Good work!")
}
If the value is not an integer, this will fail at runtime with org.json.JSONException
(as mentioned in the Javadoc linked above). You can catch this exception if you want to handle the error gracefully.
Alternatively you can use a safer option with a default value, like optInt(), which will default to the given value if the key is not present in the JSON OR if the value is not a number.
Upvotes: 2
Reputation: 2964
You need to put x["num"] as Int
into parenthesis, otherwise the compiler will think that you are trying to do Int < 2
which doesn't really make any sense.
val x = JSONObject()
x.put("num", 1)
if ((x["num"] as Int) < 2) {
print("Good work!")
}
But btw, this will throw a ClassCastException
if the value is not actually an Int
. It is in your minimal case, but you don't always actually know. In that scenario I would do something like this:
val x = JSONObject()
x.put("num", "b")
val num = x["num"]
if (num is Int && num < 2) {
print("Good work!")
}
Upvotes: 3