Mr.Smile填坑记——Kotlin中使用VasSonic时,WebResourceResponse类型转换异常

最近项目中嵌入了H5,但是启动速度很慢,于是上全球最大的同性交流平台搜索了一下,找到了VasSonic,
专注于首屏加速,由于官方demoJava的,所以开始最开始用Java实验,没有问题,但是移入项目后,发
现报错了,What the fuck???

 err kotlin.TypeCastException: null cannot be cast to non-null type android.webkit.WebResourceResponse

 什么鬼明明Java没有问题,kotlin也是自动转换的,怎么就类型转换异常了呢?先看一下Java代码

       webView.setWebViewClient(new WebViewClient() {
             @Override
             public void onPageFinished(WebView view, String url) {
                 super.onPageFinished(view, url);
                 if (sonicSession != null) {
                     sonicSession.getSessionClient().pageFinish(url);
                 }
             }

             @TargetApi(21)
             @Override
             public WebResourceResponse shouldInterceptRequest(WebView view, WebResourceRequest request) {
                 return shouldInterceptRequest(view, request.getUrl().toString());
             }

             @Override
             public WebResourceResponse shouldInterceptRequest(WebView view, String url) {
                 return sonicSession != null ? (WebResourceResponse) sonicSession.getSessionClient().requestResource(url) : null;
             }
         });

再看一下Kotlin代码

      webView.webViewClient = object : WebViewClient() {
            override fun onPageFinished(view: WebView, url: String) {
                super.onPageFinished(view, url)
                if (sonicSession != null) {
                    sonicSession!!.sessionClient.pageFinish(url)
                }
            }

            @TargetApi(21)
            override fun shouldInterceptRequest(view: WebView, request: WebResourceRequest): WebResourceResponse? {
                return shouldInterceptRequest(view, request.url.toString())
            }

            override fun shouldInterceptRequest(view: WebView, url: String): WebResourceResponse? {
                return if (sonicSession != null) sonicSession.getSessionClient().requestResource(url) as WebResourceResponse else null
            }
        }

看代码没有任何问题啊,为什么呢?

断点调试发现,VasSonic对子资源(也就是网页中包含的其他链接)sonicSession.getSessionClient().requestResource(url)都返回null,
在Java(WebResourceResponse)null只会提示没必要强转,
然而在kotlinnull as WebResourceResponse会提示肯定不会强转成功,当然类型转换异常了
至于为什么kotlin中无法强转,不是太清楚,还望大神指点一二

废话不多说了,解决代码在此

    if (sonicSession != null) {
            val requestResponse = sonicSessionClient?.requestResource(url)
            if (requestResponse is WebResourceResponse) {
                return requestResponse
            }
        }
        return null
以上代码替换三元运算那句

你可能感兴趣的:(填坑)