Take the 2-minute tour ×

In playing with Scala's combinator parsing framework, I came across the following problem when parsing floating point numbers:

import scala.util.parsing.combinator.JavaTokenParsers
import org.junit.runner.RunWith
import org.scalatest.FlatSpec
import org.scalatest.junit.ShouldMatchersForJUnit
import org.scalatest.junit.JUnitRunner

class SandboxSpec extends FlatSpec with ShouldMatchersForJUnit {
  "A java token parser" should "parse a float" in {

    class Parser extends JavaTokenParsers {
      def realValue: Parser[Float] = floatingPointNumber ^^ {
        s => s.toFloat

    val p = new Parser()
    val result = p.parseAll(p.realValue, "5.4") match {
      case p.Success(x, _)     => x
      case p.Failure(msg, _) => fail(msg)

    result should equal (5.4f plusOrMinus 0.0001f)


This test produces the following error:

5.4 did not equal FloatTolerance(5.4,1.0E-4)

I'm not sure if it's the parser code producing something not float-like (though, looking at it with the debugger, it's clearly a Java Float), or if it's an issue with the ScalaTest matcher.

Any thoughts?

share|improve this question
add comment

1 Answer

up vote 1 down vote accepted

In ScalaTest equal always means ==, thus object equality. Thus, your code does not succeed because 5.4 is not equal to an instance of FloatTolerance.

To correct your test case use be, which is overloaded to take an instance of FloatTolerance:

result should be (5.4f plusOrMinus 0.0001f)

Btw, your code throws a warning:

match may not be exhaustive. It would fail on the following input: Error(_, _)

To eliminate it choose case p.NoSuccess(msg, _) => instead of case p.Failure(msg, _) =>

share|improve this answer
I can see where I went wrong here, though the documentation (scalatest.org/user_guide/using_matchers) causes some minor confusion here, since it recommends equals for an exact comparison, and be for the the plusOrMinus case. –  Peter Schwarz Dec 17 '12 at 21:47
add comment

Your Answer


