我有以下scala代码
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")
}
Run Code Online (Sandbox Code Playgroud)
它给了我以下编译错误:
[ERROR] Class1.scala:402: error: dead code following this construct
[ERROR] r = new Gson().fromJson(m, t)
Run Code Online (Sandbox Code Playgroud)
我收到此错误的任何想法都非常感谢!
ghi*_*hik 35
看看签名的fromJson
:
public <T> T fromJson(String json, Type typeOfT)
Run Code Online (Sandbox Code Playgroud)
如您所见,此方法具有类型参数T
,但您在未指定的情况下调用它.这样,类型推断器将其理解为,new Gson().fromJson[Nothing](m, t)
并为整个表达式分配了类型Nothing
.
在Scala中,Nothing
底部类型是所有类型的子类型,没有值.返回的方法Nothing
保证永远不会返回,因为它们总是抛出异常,进入无限循环,强行终止程序(例如sys.exit()
)等等.在你的情况下,当JVM尝试强制转换时,fromJson
调用将导致ClassCastException
抛出结果来了Nothing
.因此,该调用之后的所有内容都是死代码.
这种类型的推理行为与Java不同,后者通常会new Gson().<Object>fromJson(m, t)
在这里推断出来.
归档时间: |
|
查看次数: |
5037 次 |
最近记录: |