Kotlin检测到服务器请求超时
您好我还是新的kotlin语言,当请求数据到服务器例如在Java中:
try{ request_server(); } catch(IOException e){ //Some toast for network timeout for example }
如何检查在Kotlin中是否有网络超时?
Kotlin没有检查exception,但这并不意味着你不能在Kotlin中发现IOException
。 catch
的variables声明没有区别:
try{ request_server(); } catch(e: IOException){ //Some toast for network timeout for example }
你很少看到这样的语言结构。 由于Kotlin对高阶函数有很好的支持,所以可以将error handling提取到这样一个函数中,使业务逻辑更加明显,并且可以重用。
fun timeoutHandled(block: () -> R): R { try { return block() } catch (e: IOException) { //Some toast for network timeout for example } }
像这样使用:
val result = timeoutHandled { requestServer() }