Reputation: 41
I need to use a function to print data from a data class and having read some other answers on this site, but I am still unclear on how to do it. Help would be appreciated!
data class Chemical(
val key: String,
val name : String,
val formula : String
)
fun printans(Chemical(q):: data class) {
println("Key = $q.key, Name = $q.name Formula = $q.formula")
}
fun main(args: Array<String>) {
val cuso4 = Chemical("001", "Copper(II) sulphate", "CuSO4")
val cacl2 = Chemical("002", "Calcium chloride", "CaCl2")
printans(cuso4)
printans(cacl2)
}
I have dozens of errors reported eg:
test.kt:9:22: error: expecting comma or ')'
fun printans(Chemical(q):: data class) {
test.kt:11:2: error: expecting member declaration
println("Key = $q.key, Name = $q.name Formula = $q.formula")
etc
Upvotes: 0
Views: 243
Reputation: 141
You can use Kotlin extended function feature! Like so:
fun Chemical.printans(){
println("Key = ${this.key}, Name = ${this.name} Formula = ${this.formula}")
}
And just invoke it:
val chemical = Chemical("Key", "Name", "Formula")
chemical.printans()
You can read more on extended functions here
Upvotes: 0
Reputation: 29844
Your syntax is wrong and since Chemical
is a data class, you don't even need to build the string yourself, it will already be built for you:
fun printans(c: Chemical) {
println(it)
}
Chemical(key=foo, name=bar, formula=baz)
So, you could even simplify to println(c)
, and not use a dedicated function since it does not do anything more than println
would do.
If this format is not what you want, I would recommend to override toString
of Chemical
.
data class Chemical(/* ... */) {
fun toString(c: Chemical) = "Key = ${c.key}, Name = ${c.name} Formula = ${c.formula}"
}
This way, no matter where you pass it to println
, the output will always be in your desired format, because println
calls toString
under the hood.
Upvotes: 1
Reputation: 2309
Add braces and use q: Chemical
instead Chemical(q):: data class
.
fun printans(q: Chemical) {
println("Key = ${q.key}, Name = ${q.name} Formula = ${q.formula}")
}
Upvotes: 0