Skip to content

Commit 83fdb4c

Browse files
Add File.toCSV() and List<Any>.mapToClass()
1 parent fcfd77c commit 83fdb4c

1 file changed

Lines changed: 15 additions & 1 deletion

File tree

src/main/kotlin/KotlinFunctionLibrary.kt

Lines changed: 15 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -752,7 +752,21 @@ println("workingList2=$workingList2")*/
752752
reader.close()
753753
return r
754754
}
755-
755+
756+
/**
757+
* Reads all lines of this file and constructs a new instance of [clazz].
758+
* **Warning: this uses reflection, which is has poor performance. Use kotlinx-serialization-csv if you want compile-time
759+
* efficiency**
760+
* */
761+
fun <T : Any> File.toCSV(clazz: KClass<T>): List<T> = toPath().toCSV(clazz)
762+
fun <T: Any> Path.toCSV(clazz: KClass<T>): List<T> = Files.readAllLines(this).map { it.split(",").mapToClass(clazz) }
763+
/**
764+
* Maps a list of parameters to the parameters in the primary constructor of [clazz].
765+
* **Warning: this uses reflection, which is has poor performance. Use kotlinx-serialization-csv if you want compile-time
766+
* efficiency**
767+
* */
768+
fun <T : Any> List<Any>.mapToClass(clazz: KClass<T>): T = clazz.primaryConstructor!!.call(*this.toTypedArray())
769+
756770
/**
757771
* Appends [append] to [this] if [predicate] returns true when passed [this]
758772
* Use case: it.appendLine("High-risk demographic: ".appendIf("Male(${first.ageRange.first}-${first.ageRange.last})") { demographics.size == 1 }.appendIf("Female(${first.ageRange.first}-${first.ageRange.last}") { demographics.size == 2 } )

0 commit comments

Comments
 (0)