Reputation: 509
I have a method that is supposed to return an Long.
But I get an error :
**type mismatch; found : Long required: Int**
Here is the method:
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));
}
and when I make a call to this method like this :
def IMEI() : String ={
var str: String =""
var rand:Long = 0
rand = functest.getRandom_IMEI(350000000000000,355000000000000) //error
str=rand.toString()
return str
}
I have this error:
Multiple markers at this line:
◾integer number too large
◾integer number too large
Upvotes: 4
Views: 3573
Reputation: 33387
With out being sure what your goal is, my eye catch following things.
As you write, error with the following line:
rand = functest.getRandom_IMEI(350000000000000,355000000000000) //error
you need to make it long by adding L
at the end of Long number.
rand = functest.getRandom_IMEI(350000000000000L,355000000000000L)
But you still can clean your IMEI()
method so it looks like this, there is no need to var
and you do not need to declare str
since your are returning string:
def IMEI(): String = {
val rand = getRandom_IMEI(355000000000000L, 350000000000000L)
rand.toString
}
Note: long type is specified by appending L or l suffix to the litera (link)
the other thing is your getRandom_IMEI
did not work for me as well, I did some thing simple like:
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()
}
}
Since I am do not know your final goal, but you can also use nextInt()
instead of .nextLong()
. But perhaps so you have a working code and you can do it your way. I have tested and works.
;
like Javastr
Upvotes: 1
Reputation: 1210
You have several issues, one is with your Long literals. the Random.nextInt method expects an Int argument, but to and from are Long and so is their absolute difference. If you happen to know the difference will fit in an Int you can force the result into an Int with an explicit conversion.
When you just type a number in code it is interpreted as an Int but the numbers in your code are too large to be an Int therefor you must put an "L" suffix on each number (lowercase l works as well).
As a side note multiple return statements are considered bad form, and are unnecessary. I would remove both return statements and add an else In the second method you can get rid of the last return statement and also the val assignment.
Upvotes: 0