Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cannot create an instance of an abstract class (Random)

Tags:

random

kotlin

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.

like image 674
aditya kumar Avatar asked May 23 '19 10:05

aditya kumar


People also ask

How do you fix Cannot create an instance of an abstract class?

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.

Can not create instance of abstract class or interface Kotlin?

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.

How to create abstract class object in Kotlin?

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.

What is abstract class in Kotlin?

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.


Video Answer


1 Answers

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

like image 85
DVarga Avatar answered Oct 02 '22 14:10

DVarga