0
votes

I am learning how to use Kotlin by doing tests online here: https://pl.kotl.in/P-v2WU7SH My code I'm testing is:

fun main() {
}

fun test(a: Int): Int{
    var c: Int = a*2
    return c
}

var z: Int = 5
var k: Int = test(z)
println(k)

I have 2 questions:

  1. Why does println(k) show me the error ("Expecting a top level declaration") and when I remove it I have no problem?
  2. Why when I delete fun main(){} and run my code it displays: "No main method found in project"?
2

2 Answers

0
votes

Kotlin's still bound by the same JVM rules as Java.

  • All code is initialized and run from a main method.
  • No methods can be called outside the context of any method.

So, if you put your variable declarations and your println statement into main, it'd work fine.

0
votes

Many old tutorials don't work with new versions of Kotlin. In this case, you seem to be writing a Kotlin script, whereas the compiler/IDE is likely recognizing the file as a class.

To make Kotlin scripts work on Kotlin 1.4, make the following changes:

Add this to build.gradle

implementation("org.jetbrains.kotlin:kotlin-scripting-jvm")

And rename your script file from .kt to .kts.