Since this Return keyword can automatically lift the return type,
TailCalls.done can be omitted.
import scala.util.Random
import scala.util.control.TailCalls
import scala.util.control.TailCalls.TailRec
def randomInt(): TailRec[Int] = {
while (true) {
val r = Random.nextInt(100)
if (r % 10 != r / 10) {
!Return(r)
}
}
thrownew AssertionError("Unreachable code");
}
val r = randomInt().result
r should be < 100
r % 10 should not be r / 10
,
Suppose you are generating a random integer less than 100,
whose first digit and second digit is different.
A solution is generating integers in an infinite loop,
and Return from the loop when the generated integer conforms with requirements.
import scala.util.Random
import scala.util.control.TailCalls
import scala.util.control.TailCalls.TailRec
def randomInt(): TailRec[Int] = {
while (true) {
val r = Random.nextInt(100)
if (r % 10 != r / 10) {
!Return(TailCalls.done(r))
}
}
thrownew AssertionError("Unreachable code");
}
val r = randomInt().result
r should be < 100
r % 10 should not be r / 10
This member is added by an implicit conversion from Return[ReturnValue] to
any2stringadd[Return[ReturnValue]] performed by method any2stringadd in scala.Predef.
This member is added by an implicit conversion from Return[ReturnValue] to
ArrowAssoc[Return[ReturnValue]] performed by method ArrowAssoc in scala.Predef.
This member is added by an implicit conversion from Return[ReturnValue] to
Ensuring[Return[ReturnValue]] performed by method Ensuring in scala.Predef.
Definition Classes
Ensuring
defformatted(fmtstr: String): String
Implicit information
This member is added by an implicit conversion from Return[ReturnValue] to
StringFormat[Return[ReturnValue]] performed by method StringFormat in scala.Predef.
This member is added by an implicit conversion from Return[ReturnValue] to
ArrowAssoc[Return[ReturnValue]] performed by method ArrowAssoc in scala.Predef.
A Dsl.Keyword to early return a lifted value from the enclosing function.
Author:
杨博 (Yang Bo)
Since this Return keyword can automatically lift the return type,
TailCalls.done
can be omitted.Suppose you are generating a random integer less than 100, whose first digit and second digit is different. A solution is generating integers in an infinite loop, and Return from the loop when the generated integer conforms with requirements.