我试图理解函数的正确使用(run,with,let,also,apply)。我们假设我们有以下初始代码(我将其用于测试目的):
con = urlGet.openConnection() as HttpURLConnection
con.readTimeout = 10000
con.connectTimeout = 2000
con.requestMethod = "GET"
con.doInput = true
con.connect()
inst = con.inputStream
根据这个image我将其修改为:
con = urlGet.openConnection() as HttpURLConnection
inputStream = con.run {
readTimeout = 10000
connectTimeout = 2000
requestMethod = "GET"
doInput = true
// Start the query
connect()
inputStream
}
但根据我发现的一些指南,我认为我正在做多个"工作"那里。
所以,我觉得这更正确:
con = urlGet.openConnection() as HttpURLConnection
con.apply {
readTimeout = 10000
connectTimeout = 2000
requestMethod = "GET"
doInput = true
}
inputStream = con.run {
// Start the query
connect()
inputStream
}
这些功能是如此严格分开的吗? 是否有关于如何使用这些功能的指南(官方或非正式)?
答案 0 :(得分:2)
根据official guildelines你应该使用run
,因为你从块中返回一个不同的值。所以你的第一个代码是正确的:
con = urlGet.openConnection() as HttpURLConnection
inputStream = con.run {
readTimeout = 10000
connectTimeout = 2000
requestMethod = "GET"
doInput = true
// Start the query
connect()
inputStream
}