gpt4 book ai didi

scala - 在 Scala 中,如何将 `Nothing` 用作 Fake 方法的返回值?

转载 作者:行者123 更新时间:2023-11-28 20:06:01 25 4
gpt4 key购买 nike

我想创建一个名为save 的方法,但尚未准备好实现它。但是,我不希望它在评估期间抛出异常。所以我试图让它返回一个 Nothing 作为结果。

def save[A <: AuthInfo](profile: CommonSocialProfile): Future[UserProfile] = {
// To be done
new Nothing()
}

但这行不通,编译器说:

class Nothing is abstract; cannot be instantiated

我也试过 ??? 作为占位符,但这会抛出一个 NotImplementedError,这也不符合我的需要..

def save[A <: AuthInfo](profile: CommonSocialProfile): Future[UserProfile] = ???

有没有人有更简单的方法来伪造 Scala 中的方法?

最佳答案

由于您需要返回类型为 Future[UserProfile] 的内容,因此您只需要制作一个假的 UserProfile 并返回它。

所以如果 UserProfile 定义如下:

class UserProfile(id: Int, name: String)

然后做类似的事情:

def save[A <: AuthInfo](profile: CommonSocialProfile): Future[UserProfile] = {
// To be done
Future(new UserProfile(-1, ""))
}

或者,也许您需要一个特殊的 UserProfile 单例用于此目的:

object FakeUserProfile extends UserProfile(-1, "")

def save[A <: AuthInfo](profile: CommonSocialProfile): Future[UserProfile] = {
// To be done
Future(FakeUserProfile)
}

关于scala - 在 Scala 中,如何将 `Nothing` 用作 Fake 方法的返回值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28802132/

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