paul paul - 1 year ago 72
Scala Question

define val variable visible on catch

Silly question I´m learning scala, and I found that since I´m using inmutable val I cannot define a val out of the try/catch to be visible in the catch. So in this case, what is the normal behave??

This is my code

try {
val jsonAlbum= new JSONObject(json.asInstanceOf[Map[String, Any]])
val album = AlbumFactory.create(jsonAlbum)
albums = albums ++ List(album)
} catch {
case e: NoSuchElementException => {
println(s" Excewption adding alnum:$jsonAlbum")--> This val is not visible

jsonAlbum is not visible in the catch since is not defined out of the try

Obviously I would like to keep it val and not var

Answer Source

Can val jsonAlbum= new JSONObject(json.asInstanceOf[Map[String, Any]]) throw NoSuchElementException? If not, just declare jsonAlbum before that try/catch block. If yes, you wouldn't see correct value of jsonAlbum in catch block anyway, because it's creation failed.

Note that you can use something like

val a = try { ... } catch { ... }

if you want to keep visibility without code garbage.