这是我的代码:
package net.claritysales.api.helper
import net.claritysales.api.models.UserEntity
import scala.util.Random
trait TestData {
def userInfo(
id : Long = randomLong(),
username : String = randomString(),
password : String = randomString()
) : UserEntity = {
var user : UserEntity = new UserEntity(
id = id, //Error is Long and recived Optional[Long]
username = username,
password = password)
return user}
def randomString(): String = Random.alphanumeric.take(10).mkString("")
def randomLong(): Long = Random.nextLong()
}
和UserEntity:
case class UserEntity(id: Option[Long] = None, username: String, password: String) {
require(!username.isEmpty, "username.empty")
}
和错误消息:类型不匹配,预期:选项[长],实际:长
如何将Optional [Long]转换为Long? Id是Optiona [Long] randomLong(),id必须为Long。谢谢!
答案 0 :(得分:2)
我不确定代码中的问题究竟在哪里,但我将介绍处理Option
的常用方法。 Option
解决了Java null
解决的相同问题,但它的处理方式更好,更安全,更易于使用。所以我将在这里使用一个假设函数,刚收到一个Option[A]
。你需要问自己的问题是:如果我得到None
,这意味着什么? Scala强迫您提出这个问题,其中所有类类型都隐式可为空(如Java中所示)。
或许None
表示我们从A
获得的地方失败了。出了点问题,随机发生器失败,也许我们除以零。然后我们想表明我们失败了。因此,在这种情况下,我们将函数的返回类型从A
更改为Option[A]
并返回None
。
在Java中,这看起来像这样。
if (arg == null)
return null;
return doSomething(arg);
在Scala中,
arg map { x => doSomething(x) }
如果arg
为None
,则返回None
。如果arg
包含值,则会对值运行doSomething
并在Option[A]
内返回结果。
None
表示不同的行为在某种意义上,或许None
表示我们希望函数的行为不同。在Java中,这看起来像这样。
if (arg != null) {
return doSomething(arg);
} else {
return doSomethingElse();
}
在Scala中,我们以类型安全的方式执行此操作。
arg match {
case None => doSomethingElse()
case Some(x) => doSomething(x) // Note that x is A, not Option[A]
}
None
仅为默认有时None
表示我们要使用默认值。如果我们将一堆数字相加,其中一些可能是None
,我们希望None
等同于数值0
,这样它就不会改变我们的结果
在Java中,我们可能会写,
int x = 0;
if (arg != null)
x = arg;
return doSomething(x);
在Scala中,我们可以使用getOrElse
更简洁地完成此操作。
doSomething(arg.getOrElse(0))
在我们的案例中,也许None
真的很糟糕。也许这是调用代码中的一个错误,我们根本没有能力处理。也许我们的功能只是 waaaay 太重要了,如果它失败了,那么其他一切都会被没收。然后我们可以提出异常。请注意,这种方法在Scala中并不是非常惯用,所以只有在没有任何意义的情况下才能非常谨慎地使用它。
在Java中,
if (arg == null)
throw new RuntimeException("Oops!");
return doSomething(arg);
在Scala中,
arg match {
case None => sys.error("Oops!")
case x => doSomething(x)
}
答案 1 :(得分:1)
问题不在于您有Option[Int]
并需要Int
(正如您在问题的标题和正文中所声称的那样)。这是你有Int
并且需要Option[Int]
。这是因为userInfo
需要Int
,但UserEntity
需要Option[Int]
。
要解决此问题,您只需将Some(id)
作为参数传递。
答案 2 :(得分:0)
使用get或者,我不知道在你的情况下什么给予无案
var user : UserEntity = new UserEntity(
id = id.getOrElse(0l)
username = username,
password = password)
return user}