https://kotlinlang.org logo
#getting-started
Title
# getting-started
b

Ben Edwards

08/18/2022, 5:13 PM
Sorry, me again, hope people don't mind. In the JetBrains tutorial it has the following code
*val* reader = FileReader("test.txt")
reader.*use* {
reader.read()
}
Which can be replaced by
FileReader("test.txt").use { reader -> read("something") }
Which I am confused by, what is "something" referring to?
j

Joffrey

08/18/2022, 5:19 PM
I think that must be a mistake
☝️ 3
b

Ben Edwards

08/18/2022, 5:22 PM
Certainly felt like they may be, so what should it be?
FileReader("test.txt").use { reader -> read() }
👎 1
🆗 1
m

Matthew Gast

08/18/2022, 5:24 PM
You'll probably want to use
reader.read()
as
use
is does not scope
Reader
but passes it as a parameter (which is what the
reader ->
is).
1
j

Joffrey

08/18/2022, 5:25 PM
Matthew is right. You should use either of those:
FileReader("test.txt").use { reader -> reader.read() }
FileReader("test.txt").use { it.read() }
r

Ruckus

08/18/2022, 5:41 PM
Or, with a function reference
Copy code
FileReader("test.txt").use(Reader::read)
i

ilya.gorbunov

08/18/2022, 9:49 PM
Since
use
passes its receiver as a parameter to the provided lambda, the following two are equivalent:
reader.use { reader.read() }
and
reader.use { it.read() }
2 Views