Kotlin标准函数:run、with、let和apply
我试图理解函数的正确用法(run、with、let、allow、apply)。假设我们有以下初始代码(我使用它进行测试): 根据这一点,我将其修改为:Kotlin标准函数:run、with、let和apply,kotlin,Kotlin,我试图理解函数的正确用法(run、with、let、allow、apply)。假设我们有以下初始代码(我使用它进行测试): 根据这一点,我将其修改为: con = urlGet.openConnection() as HttpURLConnection inputStream = con.run { readTimeout = 10000 connectTimeout = 2000 requestMethod = "GET" doInput = true // St
con = urlGet.openConnection() as HttpURLConnection
inputStream = con.run {
readTimeout = 10000
connectTimeout = 2000
requestMethod = "GET"
doInput = true
// Start the query
connect()
inputStream
}
但根据我找到的一些指南,我认为我在那里做了多项“工作”。- 修改初始con对象
- 运行更多功能(连接)
- 获取另一个对象(inputstream)
con = urlGet.openConnection() as HttpURLConnection
con.apply {
readTimeout = 10000
connectTimeout = 2000
requestMethod = "GET"
doInput = true
}
inputStream = con.run {
// Start the query
connect()
inputStream
}
这些功能是如此严格地分开的吗?是否有关于如何使用这些功能的指南(官方或非官方)?根据,您应该使用
运行,因为您从块返回的值不同。因此,您的第一个代码是正确的:
con = urlGet.openConnection() as HttpURLConnection
inputStream = con.run {
readTimeout = 10000
connectTimeout = 2000
requestMethod = "GET"
doInput = true
// Start the query
connect()
inputStream
}
一个通用的习惯用法是使用apply
inline:con=(urlGet.openConnection()作为HttpUrlConnection)。apply{…}
。这就像是扩展初始化过程。
con = urlGet.openConnection() as HttpURLConnection
inputStream = con.run {
readTimeout = 10000
connectTimeout = 2000
requestMethod = "GET"
doInput = true
// Start the query
connect()
inputStream
}