Captiulo 1, Kotlin in Action, Expecting a top level declaration [Beginner]

Asked

Viewed 337 times

0

I’m learning Kotlin, I can’t understand why the problem "Expecting a top level declaration". The result I intended was that I pointed out Bob as the oldest

data class Person(val name: String,
val age: Int? = null)

fun main(args: Array<String>) {
val persons = listOf(Person("Alice"),
                        Person("Bob", age = 29))
val oldest = persons.maxBy { it.age ?: 0 } }

println("The oldest is: $oldest")

I copied it just like the book but keeps returning it down

Expecting a top level declaration Expecting a top level declaration Expecting a top level declaration Expecting a top level declaration Expecting a top level declaration Expecting a top level declaration Expecting a top level declaration Expecting a top level declaration

  • your println is out of main function

1 answer

1


Its println function was outside the main function, in case the lock key "}" came before.

I tested it here on Intellij and the code works.

As you can see the only change I made in this code, was to remove the parameter from the "main" function to run in Intellij.

package testes

data class Person(val name: String, val age: Int? = null)

fun main() {
    val persons = listOf(Person("Alice"), Person("Bob", age = 29))
    val oldest = persons.maxBy { it.age ?: 0 }

    println("The oldest is: $oldest")
}

Upshot:

inserir a descrição da imagem aqui

Browser other questions tagged

You are not signed in. Login or sign up in order to post.