Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/html/77.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Scala 类型失配;找到:Long必需:Int_Scala - Fatal编程技术网

Scala 类型失配;找到:Long必需:Int

Scala 类型失配;找到:Long必需:Int,scala,Scala,我有一个方法,应该返回Long。 但我得到一个错误: **类型不匹配;找到:需要较长时间:Int** 方法如下: def getRandom_IMEI(from : Long,to : Long) : Long = { if (from < to) return from + new scala.util.Random().nextInt(Math.abs(to - from)); return from - new scala.util.Random().

我有一个方法,应该返回Long。 但我得到一个错误:
**类型不匹配;找到:需要较长时间:Int**

方法如下:

def getRandom_IMEI(from : Long,to : Long) : Long = {
    if (from < to)
        return from + new scala.util.Random().nextInt(Math.abs(to - from));
    return from - new scala.util.Random().nextInt(Math.abs(to - from));
   }
我有一个错误:

    Multiple markers at this line:
        ◾integer number too large
        ◾integer number too large

您有几个问题,一个是您的长文本。 Random.nextInt方法需要一个Int参数,但to和from都很长,它们的绝对差也是如此。 如果您碰巧知道差异将适用于Int,则可以通过显式转换将结果强制转换为Int

当您在代码中键入一个数字时,它会被解释为Int,但代码中的数字太大,不能成为Int,因此您必须在每个数字上加一个“L”后缀(小写L也可以)

作为旁注,多个返回语句被认为是糟糕的形式,并且是不必要的。我将删除这两个return语句并添加一个else
在第二种方法中,可以去掉最后一个return语句和val赋值

在不确定你的目标是什么的情况下,我注意到了以下几点

写入时,出现以下错误行:

rand = functest.getRandom_IMEI(350000000000000,355000000000000)  //error
您需要在长数字的末尾添加
L
,使其变长

rand = functest.getRandom_IMEI(350000000000000L,355000000000000L)
但是您仍然可以清理
IMEI()
方法,因此看起来是这样的,不需要
var
,也不需要声明
str
,因为您正在返回字符串:

def IMEI(): String = {
  val rand = getRandom_IMEI(355000000000000L, 350000000000000L)
  rand.toString
}
注意:long类型是通过在 文字()

另一件事是你的
getRandom\u IMEI
也不适合我,我做了一些简单的事情,比如:

def getRandom_IMEI(from: Long, to: Long): Long = {
  if (from < to) {
    from + new scala.util.Random(to - from).nextLong()
  } else {
    from - new scala.util.Random(to - from).nextLong()
  }
}
def getRandom_IMEI(from:Long,to:Long):Long={
如果(从<到){
from+new scala.util.Random(to-from.nextLong())
}否则{
from-new scala.util.Random(to-from.nextLong()
}
}
因为我不知道您的最终目标,但您也可以使用
nextInt()
而不是
.nextLong()
。但也许你有一个工作代码,你可以用你自己的方式来做。我已经测试和工作

  • 在Scala中,一般规则是不需要在每一行末尾加上
    类似Java
  • 您不需要返回,它将自动返回最后一条语句,因此您可以轻松地从第二个方法中删除返回,只需保留
    str

在IMEI函数中使用
val
而不是
var
-您只分配了一次。
def getRandom_IMEI(from: Long, to: Long): Long = {
  if (from < to) {
    from + new scala.util.Random(to - from).nextLong()
  } else {
    from - new scala.util.Random(to - from).nextLong()
  }
}