gpt4 book ai didi

java - 如何在不运行App(main)的情况下初始化App的成员?

转载 作者:行者123 更新时间:2023-12-02 03:44:21 27 4
gpt4 key购买 nike

我有一个类MyClass,它扩展了App。问题是,在 MyClass 内部,有一个我需要初始化的变量 myValue,而无需实际运行应用程序。这样做的原因是因为我想以非交互式方式运行 MyClass 方法的单元测试。

class MyClass extends App {
val myValue = "A value that I need to run the unit tests"

def myMethod: Unit = "A method that needs to be unit-tested and uses " + myValue

/* ... main (interactive) code that is not supposed to run in the unit test... */
}

所以,问题是:如何在不运行应用程序(主)的情况下初始化应用程序的成员?

最佳答案

来自 App 特征的 scaladocs:

==Caveats==

It should be noted that this trait is implemented using the DelayedInit functionality, which means that fields of the object will not have been initialized before the main method has been executed.

看来你唯一的选择是声明 main 方法 def main(args: Array[String]): Unit = ... 就像在 Java 中所做的那样,而不是扩展 App .

关于java - 如何在不运行App(main)的情况下初始化App的成员?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36461296/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com