I'm new to OOP and Kotlin. For some reason on line 12 of my code, "println(mapOfArithmetic)", I am being given the error that it needs a member declaration. Please help me explain what exactly this is and how I can fix it. Thanks.
package entities
class Flashcard2() {
val mapOfArithmetic = mapOf("1 1" to "=2", "2 2" to "=4",
"3 3" to "=6", "4 4" to "=8",
"5 5" to "=10", "6 6" to "=12",
"7 7" to "=14", "8 8" to "=16",
"9 9" to "=18", "10 10" to "=20")
println(mapOfArithmetic)
}
class FlashcardSet2(var mapOfArithmetic: Map<String, String>) {
}
CodePudding user response:
Currently, you have a method call directly inside a class declaration, which is invalid.
What you actually need is to declare a metho within Flashcard2 so that println(mapOfArithmetic) is a valid statement:
class Flashcard2() {
val mapOfArithmetic = mapOf("1 1" to "=2", "2 2" to "=4",
"3 3" to "=6", "4 4" to "=8",
"5 5" to "=10", "6 6" to "=12",
"7 7" to "=14", "8 8" to "=16",
"9 9" to "=18", "10 10" to "=20")
fun print() = println(mapOfArithmetic)
}
CodePudding user response:
As João Dias already pointed out, it is not possible to have a function call directly inside your class. So one possible solution is to declare a function and call the println inside it.
If you want to have the output on every instantiation of your class Flashcard2, it would instead be better to put the call inside a constructor:
class Flashcard2 {
val mapOfArithmetic = mapOf("1 1" to "=2", "2 2" to "=4",
"3 3" to "=6", "4 4" to "=8",
"5 5" to "=10", "6 6" to "=12",
"7 7" to "=14", "8 8" to "=16",
"9 9" to "=18", "10 10" to "=20")
constructor() {
println(mapOfArithmetic)
}
}
Alternatively, you can call it inside an init block:
class Flashcard2() {
val mapOfArithmetic = mapOf("1 1" to "=2", "2 2" to "=4",
"3 3" to "=6", "4 4" to "=8",
"5 5" to "=10", "6 6" to "=12",
"7 7" to "=14", "8 8" to "=16",
"9 9" to "=18", "10 10" to "=20")
init {
println(mapOfArithmetic)
}
}
This way you do not need the definition of a function, and the expression is called on any instantiation of the class.
