I am trying to learn Kotlin so I was following a tutorial on internet where instructor wrote a code which worked fine in with them but it gives error to me.
This is the error
Error:(26, 17) Kotlin: Cannot create an instance of an abstract class
import kotlin.random.Random
fun main(args: Array<String>) {
feedTheFish()
}
fun feedTheFish() {
val day = randomDay()
val food = "pellets"
print("Today is ${day} and the fish eat ${food}")
}
fun randomDay():String {
val week = listOf ("Monday", "Tuesday", "wednesday", "thursday", "friday", "saturday", "sunday")
return week[ Random().nextInt(7)]
}
I am getting error from return statement, I think from Random. Please help me to understand this and fix this code.
Solution. In Kotlin, we cannot create an instance of an abstract class. Abstract class could only be inherited by a class or another Abstract class. So, to use abstract class, create another class that inherits the Abstract class.
In Kotlin, we cannot create an instance of an abstract class. Abstract classes can only be implemented by another class which should be abstract in nature. In order to use an abstract class, we need to create another class and inherit the abstract class.
We can't create an object for abstract class. All the variables (properties) and member functions of an abstract class are by default non-abstract. So, if we want to override these members in the child class then we need to use open keyword.
A Kotlin abstract class is similar to Java abstract class which can not be instantiated. This means we cannot create objects of an abstract class. However, we can inherit subclasses from a Kotlin abstract class. A Kotlin abstract class is declared using the abstract keyword in front of class name.
Just remove the parentheses: Random.nextInt(7)
.
Like this it uses the companion object (Default
) of class Random
which implements the abstract class Random
with a default behaviour.
From the documentation:
The companion object Random.Default is the default instance of Random
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With