Javap difference when compiling with / without approval

Scala for the portable chapter 15 Exercise 10: add assert(n >= 0 to the factorial method. Compile with the statements included and make sure factorial(-1) throws an exception. Compile without statements. What happens? Use javap to check what happened with a confirmation call.

My code is:

 object Test { def factorial(x: Int): Int = { assert(x >= 0, "Call to factorial must be >= 0!") x match { case 0 => 1 case x: Int => x * factorial(x - 1) } } def main(args: Array[String]): Unit = { factorial(-1) } } 

First I compiled scalac , examined it with javap Test , then compiled again with scalac -Xelide-below MAXIMUM and examined with the same command - I can not find the difference between them.

I understand that compilation with statements throws an exception when trying to execute a program, and compilation without statements will throw an error, but I cannot find the difference in javap ...

+4
source share
1 answer

When I try to do this with javap -v , I find the following lines in the version with claims included, but not in another:

  20: invokevirtual #27; //Method scala/Predef$.assert:(ZLscala/Function0;)V ... 27: if_icmpne 34 30: iconst_1 31: goto 55 

So, of course, everything is in order.

The problem may be that you are either not looking at the bytecode (which requires the -c or -v for javap ), or, much more likely, you are looking at the javap output for the Test class, not Test$ . For more details see Programming in Scala :

For each Scala singleton object, the compiler will create a Java class for the object with a dollar sign added to the end. For a singleton object named App , the compiler creates a Java class named App$ . This class has all the methods and fields of a Scala single object.

If you list the contents of the directory into which you compiled, you will see both Test.class and Test$.class . Using javap -v Test$ will show you the last one in which you will find the difference.

+5
source

All Articles