I am new to Kotlin and find it confusing at times (never done java either). Having done the basics of Kotlin in the past couple of weeks coding simple things I now find myself learning classes. I am trying to return an array from a method in a simple class. The goal of this code is to check if a file exists and if it is readable then open it for reading and lastly print the contents of it.
I am aware that my “style” is not correct and maybe I am using the wrong array type so I will appreciate it if you could steer me in the right direction in how to write the below code differently or more efficiantly. The link to the names.txt
file is here
import java.io.*
import java.util.*
import java.text.*
fun main(){
var checkFileProperties = PersonalData("names.txt");
println(checkFileProperties) // Prints -> PersonalData(nameOfFile=names.txt)
/*
//If I do the lines below I get the following error: "For-loop range must have an 'iterator()' method"
for ( resultCheckFileProperties in checkFileProperties ){
print(resultCheckFileProperties)
}
*/
}
data class PersonalData ( val nameOfFile: String ) {
val fileDir = "C:\\Users\\Flower\\Documents\\learn\\kotlin\\resources" ; //where the txt files are stored
val nameFile = File("${fileDir}\\${nameOfFile}")
var dataReturnValue: MutableList<String> = ArrayList()
private fun checkFileExists(): MutableList<String> {
var fileExists = nameFile.exists()
if ( fileExists ){
dataReturnValue.add("true")
var fileRead = nameFile.canRead()
if ( fileRead ) {
dataReturnValue.add("true")
} else {
dataReturnValue.add("false")
}
} else {
dataReturnValue.add("false")
}
return dataReturnValue
}
}
Summary
Thank you