4

I am trying to understand the correct use of the functions (run, with, let, also, apply). Let's say we have the following initial code (I am using it for testing purposes):

con = urlGet.openConnection() as HttpURLConnection
con.readTimeout = 10000
con.connectTimeout = 2000 
con.requestMethod = "GET"
con.doInput = true
con.connect()
inst = con.inputStream

According to this image I modified it to:

con = urlGet.openConnection() as HttpURLConnection
inputStream = con.run {
   readTimeout = 10000
   connectTimeout = 2000
   requestMethod = "GET"
   doInput = true
   // Start the query
   connect()
   inputStream
}

But according to some guides I found, I think that I am doing multiple "jobs" there.

  • modify the initial con object
  • run some more functions (connect)
  • get another object back (inputstream)

So, I am feeling that this is more correct:

    con = urlGet.openConnection() as HttpURLConnection
    con.apply {
           readTimeout = 10000
           connectTimeout = 2000
           requestMethod = "GET"
           doInput = true
        }
    inputStream = con.run {
           // Start the query
           connect()
           inputStream
        }

Are those functions so strictly separated?
Are there any guides (official or not) on how to use these functions?

LiTTle
  • 1,811
  • 1
  • 20
  • 37
  • 1
    One general idiom is to use `apply` inline: `con = (urlGet.openConnection() as HttpUrlConnection).apply { ... }`. It's like extending the initialization procedure. – Marko Topolnik Apr 30 '18 at 13:40
  • https://stackoverflow.com/questions/45582732/when-should-we-use-let-also-apply-takeif-takeunless-in-kotlin?rq=1 – Vijay Makwana May 01 '18 at 06:16

1 Answers1

2

According to the official guildelines you should be using run because you return a different value from the block. So your first code is correct:

con = urlGet.openConnection() as HttpURLConnection
inputStream = con.run {
   readTimeout = 10000
   connectTimeout = 2000
   requestMethod = "GET"
   doInput = true
   // Start the query
   connect()
   inputStream
}
Nikolay Kulachenko
  • 4,604
  • 4
  • 31
  • 37