I use nashorn in my project. I want get property from a json, but property may not have value.
In javascript, use optional chaining and set a value, if property is null; but in nashorn, when I use (?.), I get this error:
import org.springframework.stereotype.Service
import javax.script.ScriptEngineManager
import javax.script.Bindings
@Service
class SampleService {
class Person(
val firstName: String,
val lastName: String,
val child: Child?
)
class Child(
val name: String,
val age: Int
)
fun runScript() {
val engine = ScriptEngineManager().getEngineByName("nashorn")
val bindings: Bindings = engine.createBindings()
val person = Person("John", "Smite", null)
bindings["person"] = person
try {
val script = """
var childAge = person.child?.age ?? 0;
childAge; //return as result.
""".trimIndent()
val scriptResult: Any = engine.eval(script, bindings)
} catch (e: Exception) {
throw e
}
}
}
I get this error:
javax.script.ScriptException: <eval>:1:28 Expected an operand but found .
var childAge = person.child?.age ?? 0;
^ in <eval> at line number 1 at column number 28
I checked this link, but I could not solve the problem: Optional chaining (?.)
How can I fix this error?