Expecting member declaration
Expecting member declaration
DodaTech
3 min read
The “Expecting member declaration” error means the Kotlin parser found a statement or expression where it expected a class, function, or property member declaration.
What It Means
Kotlin source files are organised into declarations: packages, imports, classes, functions, and properties at the top level. Inside a class, only member declarations (properties, methods, nested classes) are allowed. When the parser encounters executable code or a misplaced declaration in a position where only member declarations are valid, it reports “Expecting member declaration.”
Why It Happens
- Executable code (like
println()) is placed directly inside a class body instead of inside a function. - A closing brace
}is missing, causing the parser to misinterpret subsequent code as part of the same class. - A function declaration is accidentally placed inside another function without using a local function syntax.
- An
importstatement is placed inside a class or function instead of at the top of the file. - An annotation or modifier is used in an invalid position.
- A semicolon or comma is misplaced, confusing the parser.
How to Fix It
1. Move executable code inside a function
// ❌ Expecting member declaration
class Greeter {
println("Hello") // executable code inside class body
}
// ✅ Wrap in a function
class Greeter {
fun greet() {
println("Hello")
}
}2. Close all braces properly
// ❌ Missing closing brace for the class
class User {
val name: String = "Alice"
fun display() {
println(name)
}
// Missing } causes parser to misinterpret the next class as a member
// ✅ Every brace must have a matching close
class User {
val name: String = "Alice"
fun display() {
println(name)
}
}3. Keep imports at the top of the file
// ❌ Import inside a class
class Parser {
import java.io.File // wrong position
fun read(path: String) = File(path).readText()
}
// ✅ Import at the top level
import java.io.File
class Parser {
fun read(path: String) = File(path).readText()
}4. Don’t place functions inside other functions without a local function
// ❌ Nested function without proper syntax
fun outer() {
println("Start")
fun inner() {
println("Inside")
}
// Missing call — but the declaration itself is valid as a local function
inner()
}
// This is actually valid Kotlin! The error usually comes from something else
// nearby. Check for missing braces above this function.5. Check for misplaced annotations and modifiers
// ❌ Annotation in wrong position
class @Deprecated Parser { }
// ✅ Annotation before the declaration
@Deprecated
class Parser { }Built by the developers of DodaTech
Doda Browser, DodaZIP & Durga Antivirus Pro