Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why do I get 'Dead code following this construct' with the following code?

Tags:

I have following scala code

def message(attachmentId: UUID) : URI = {   var r : mutable.MutableList[BasicTemplate] = new mutable.MutableList[BasicTemplate]   val t : Type = new TypeToken[Iterable[BasicTemplate]](){}.getType()   val m : String = "[{\"basicTemplate\":\"TEMPLATE\",\"baseline\":\"DEMO\",\"identifier\":\"0599999999\"}]"    r = new Gson().fromJson(m, t)   Console.println(r.head.getBasicTemplateName)    URI.create("http://google.com") } 

And it gives me following compilation error:

[ERROR] Class1.scala:402: error: dead code following this construct [ERROR] r = new Gson().fromJson(m, t) 

Any ideas why I get this error are highly appreciated!

like image 654
AVE Avatar asked Feb 26 '14 15:02

AVE


1 Answers

Look at the signature of fromJson:

public <T> T fromJson(String json, Type typeOfT) 

As you can see, this method has type parameter T, but you called it without specifying it. This way, type inferencer understood it as new Gson().fromJson[Nothing](m, t) and the entire expression was assigned the type Nothing.

In Scala, Nothing is a bottom type that is a subtype of all types and has no values. Methods that return Nothing are guaranteed to never return, either because they always throw an exception, fall into infinite loop, forcibly terminate the program (e.g. sys.exit()), etc. In your case, the fromJson call will cause a ClassCastException to be thrown when the JVM tries to cast its result to Nothing. Therefore, everything after that call is a dead code.

This type inference behaviour is different from Java, which would normally infer new Gson().<Object>fromJson(m, t) here.

like image 58
ghik Avatar answered Jan 20 '23 17:01

ghik