Andrew Gazelka
01/08/2019, 5:40 PMinit{}
occur after init and if so, is it a good practice if order matters to include it in init{}
?
i.e.,
class Logger(val logFile: Path)
{
val writer = Files.newBufferedWriter(logFile)
init {
if(!Files.exists(logFile))
{
Files.createFile(logFile)
}
}
}
diesieben07
01/08/2019, 5:44 PMwriter
would be initialized before the init
block.
You can have multiple init
blocks as well.Andrew Gazelka
01/08/2019, 5:45 PMaltavir
01/08/2019, 5:45 PMinit
block is a sore spot for kotlin. One should avid using it if possible and not place something sensitive there.diesieben07
01/08/2019, 5:46 PMaltavir
01/08/2019, 5:46 PMShawn
01/08/2019, 5:46 PMwriter
declaration and attempting to use it there - you should get an error to the effect of Variable 'writer' must be initialized
altavir
01/08/2019, 5:47 PMdiesieben07
01/08/2019, 5:47 PMaltavir
01/08/2019, 5:49 PMaltavir
01/08/2019, 5:49 PMAndrew Gazelka
01/08/2019, 5:53 PMinit{}
blocks are bad like Java blocks are bad?Andrew Gazelka
01/08/2019, 5:55 PMconstructor
?altavir
01/08/2019, 5:56 PMaltavir
01/08/2019, 5:56 PMAndrew Gazelka
01/08/2019, 6:00 PMShawn
01/08/2019, 6:02 PMval
usage. Maybe a factory method and a modified constructor would be the best way to goaltavir
01/08/2019, 6:03 PMAlan Evans
01/08/2019, 6:20 PMinit
by use of lazy:
class Logger(val logFile: Path) {
val writer by lazy {
if (!Files.exists(logFile)) {
Files.createFile(logFile)
}
Files.newBufferedWriter(logFile)
}
}
It changes the behaviour somewhat but is better because it keeps the code that creates the file together with the usage of the new file.Alan Evans
01/08/2019, 6:21 PMAlan Evans
01/08/2019, 6:23 PM