【问题标题】:Cannot create an instance of an abstract class (Random)无法创建抽象类的实例(随机)
【发布时间】:2019-05-23 18:26:26
【问题描述】:

我正在尝试学习 Kotlin,所以我在网上学习了一个教程,其中讲师编写了一个代码,在他们身上运行良好,但它给了我错误。

这是错误

错误:(26, 17) Kotlin: 无法创建抽象类的实例

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)]
}

我从 return 语句中得到错误,我认为是随机的。请帮助我理解这一点并修复此代码。

【问题讨论】:

    标签: random kotlin


    【解决方案1】:

    只需去掉括号:Random.nextInt(7)

    像这样,它使用类 Random 的伴随对象 (Default),它以默认行为实现抽象类 Random

    来自documentation

    伴随对象 Random.Default 是 Random 的默认实例

    【讨论】:

      【解决方案2】:

      这是因为您试图调用抽象类的函数,但抽象类没有实例。相反,您可以使用随机伴随对象中的静态函数

      Random.nextInt(yourIntValue)
      

      【讨论】:

        猜你喜欢
        • 2019-11-23
        • 2019-04-07
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多