I am trying to run this specific file and it will not allow me to run it. It states that init should return void. I’m not too sure what that means but it doesn’t sound correct. Either way it will not allow me to run the program.
Here is the code:
package com.example.classesandoop;
import static java.sql.DriverManager.println;
class Dog {
init {
bark();
}
fun bark() {
println("Woof Woof");
}
}
I did not try many options as this should be cookie cutter from the tutorial I am following. Updated Image below shows the error codes. After updating the code it states the init function needs an identifier and the remaining lines of code require semicolons.
2
Answers
This is not a valid Android source code to be run. So why are you using Android Studio?
If this should be Kotlin, there should not be semicolons at the end of lines, kotlin does not use it this way, as oposed to Java.
You are importing wrong function, from sql.DriverManager which is part of SQL to work with Databases.
And your code is missing the main function to be executed.
When you run the file, the main function will be executed. It will create an instance of your class Dog, which will invoke your init part and via method bark print to the console. It will be invoked on your computer, not on the Android device.
From your screenshot it looks like you try to write Kotlin code into a Java file. Although you can mix Kotlin and Java code this cannot be done in a single file. So you must decide which you want:
You just need to rename your file to
Dog.kt
and it should work, assuming you set up your build environment to proplerly compile Kotlin.Also, you only need semicolons to separate multiple commands on the same line. If you only have one per line (as it usually is) you don’t need semicolons in Kotlin at all.