Initialization of an interface of Strings in Groovy - class

interface PRINT {
def LN = '\n\n'
def BREAK = '='*80
}
println PRINT.BREAK
I'm getting this error while trying to initialize BREAK:
java.lang.NoClassDefFoundError: PRINT$1
There's an issue with '='*80, what could be the reason and what would be a better approach for this?
It works without the multiplication.
Thanks for helping out.

Related

Override RootMonitor

I have some code running inside Future.respond, that throws an NPE, because of a bug. The problem is that my unit tests totally missed it, and are all happily passing, because the NPE is swallowed by the RootMonitor.
So, my question is if there is any way to override the RootMonitor behavior for the unit tests to result in a test failure rather than swallowing the exception?
I know, I could just catch the exception inside respond, but that's kinda backwards - if I thought there could be an exception, I would've fixed it in the first place. That's exactly a kind of situation I would like my test to catch.
So, what I am looking for is a way to override the RootMonitor globally for the tests, or else to assert somehow that it handled no exceptions after the test finishes.
Is there a way to do something like this? How do people usually deal with this kind of tests?
Ok, I think, I found a solution. It seems a bit kludgy, so if someone can come up with a better way, please chime in, but here goes.
class MonitoredSuite extends FunSuite {
protected override def withFixture(test: NoArgTest): Outcome = {
var exception: Throwable = null
Monitor.using(Monitor.mk {
case e =>
exception = e
false
})(test()) match {
case x#Exceptional(_) => x
case s if exception == null => s
case _ => Exceptional(exception)
}
}
}
Basically, I install a noop monitor before each test, and then generate a failure if it was invoked.

Scalastyle Boolean expression can be simplified

Scalastyle (intellij 2016.1 defaults) says this boolean expression can be simplified
val t = Option(true)
val f = Option(false)
if(t.contains(true) && f.contains(false)) {
println("booop")
}
I can get rid of this by changing the if to:
if(t.contains(true).&&(f.contains(false)))
Or by changing && to &
But not really seeing how this is simplifying it, could anyone explain what's going on?
Update
It doesn't appear to be related to if the vals are known at compile time, or them being locally defined. The following code also get's the warning that the expression can be simplfied:
object TestFoo {
def bar(t: Option[Boolean]) = {
val f = Option(scala.util.Random.nextBoolean)
if (t.contains(true) && f.contains(false)) println("booop")
}
def main(args: Array[String]) = bar(t = Option(scala.util.Random.nextBoolean))
}
I just don't get how I'm supposed to make that any simpler, is there some strange Option[Boolean] comparing I'm missing out on?
It seems to suggest you being consistent with the method call usage. Either everything in infix form:
(t contains true) && (f contains false)
Or everything in regular method call form:
t.contains(true).&&(f.contains(false))
With your values, t.contains(true).&&(f.contains(false)) always returns true. So you could simplify it by simply writing true, i.e by just executing the print without an if condition.

Diagnosing Scala compile error "value to is not a member of Int"

I made a code change within a Scala class that had been working fine. Upon trying to compile the modification, the compiler spit out the error message, "value to is not a member of Int" relating to this (pre-existing) line of code:
for (i <- 0 to cColumn -1) { ... }
Doing some research, I came across some bug reports on the "to" method - and also that "to" is apparently a method provided within the intWrapper class(?).
So, based upon that info, I started looking at my class's import statements... no such import for intWrapper. (Q: That being the case, how did this ever compile/run in the first place?) What makes this even more interesting (to me) is that when I started to do a global search in the codebase for that import I accidentally terminated the compiler (sbt) session...but when I restarted it, the class compiled just fine. No errors at all. (And no code changes from the previous session)
Anyone have any ideas as to what would cause this intermittent behavior?
NOTES:
1) using Scala 2.10.2 with javac 1.7.0_25
2) the code change to the class had nothing to do with the example functionality, nor did it alter any of the class's imports
Update: Here are the variable declarations:
val meta = rs.getMetaData()
val cColumn = meta.getColumnCount()
EDIT: Per suggestion, here is the test lines (all of them compile fine now):
implicitly[scala.Int => scala.runtime.RichInt]
intWrapper(3) to 4
for (i <- 0 to 33 -1) { /* do something smart */ }
for (i <- 0 to cColumn -1) { ... }
EDIT 2 Here is the full compiler error:
[error] /path/to/src/file/DBO.scala:329: value to is not a member of Int
[error] for (i <- 0 to cColumn -1) {
[error]
That error was repeating ~18 times in the class. (It's a DBO-DB interface layer); where DBO.scala is the file containing the newly modified trait.
I just encountered this same issue. In my case, it was caused by an unnecessary import, like this:
import scala.Predef.String
class Test() {
for (t <- 1 to 3) {}
}
By default, Scala imports all of scala.Predef. Predef extends LowPriorityImplicits, which includes an implicit conversion from Int to RichInt.
to is actually defined on RichInt, so you need this conversion in order to use it. By importing just part of Predef, I lose this conversion. Get rid of the unnecessary import and the error goes away.
how did this ever compile/run in the first place?
By default, the contents of scala.Predef is imported. There you have method intWrapper which produces a RichInt with method to.
You probably have shadowed symbol intWrapper. Does the following work:
implicitly[scala.Int => scala.runtime.RichInt]
or this:
intWrapper(3) to 4
...if not, there lies your problem.
EDIT: So, since you say that compiles, what happens is you replace cColumn with a constant, e.g.
for (i <- 0 to 33 -1) { ... }
? It would also help to post the complete compiler message with indicated line etc.
Without knowing where that error comes from, you might also try to work around it by constructing the Range by hand:
for (i <- Range.inclusive(0, cColumn-1)) { ... }
or
Range.inclusive(0, cColumn-1).foreach { i => ... }

How to println(something) but doesn't print anything to the console

I have a requirement to println(something) but doesn't println anything and no new line printed, how can I do that in Scala?
What should 'something' above in println be so that it satisfies my requirement?
scala> Console.setOut(new java.io.PrintStream(new java.io.OutputStream() { def write(b: Int) {} }))
scala> println("test")
scala>
I'm just relating Florian Hars reply from the google scala-user mailing list, which seems to better frame the point.
Let me restate your problem: you have an assignment where you need to ignore comments while parsing some code source file.
Actually you have a main definition to test the assignment which prints out the result of parsing the source file, and you want the println statement to ignore the parsed comments, so the teacher's condition will be met.
If this is the case, then the "correct" solution would not be to find a way to prevent println to print, but to modify the parser/lexer to avoid producing a parsed token when it encounters a comment.
The other way would just be a "trick" to get the assignment right by exploiting a particular "code configuration"...
println(...) will always print a newline, no matter what argument you pass it. There is no way to prevent it from printing a newline.
Well... there's ofcourse the following trick, but it's not very practical.
class Magic {
override def toString = throw new RuntimeException
}
// Will not print a newline, but will throw an exception
println(new Magic)
// So you'll need to catch it
try {
println(new Magic)
} catch {
case e: RuntimeException => // Ignore the exception
}
// Hey, we're here and no newline was printed!
if you're still running the scala interpreter, you can exit it by entering the :quit command. Put this into a file named hello.scala:
println("Hello, world, from a script!")
then run:
scala hello.scala
And you should get yet another greeting:
Hello, world, from a script!

How to set an expected exception using Scala and JUnit 4

I want to set an expected exception for a JUnit 4 test using Scala. I am current doing something similar to the following:
#Test(expected=classOf[NullPointerException])
def someTest() = {
// Some test code
}
But I get the following compiler error:
error: wrong number of arguments for constructor Test: ()org.junit.Test
This is looking forward a bit, but the syntax for annotations in 2.8 has changed to be the same as what you originally posted. The syntax Tristan posted is correct in the current stable version, but it gave me errors when I upgraded my project to a nightly 2.8 compiler. I'm guessing this is due to the inclusion of named and default arguments. There is also some discussion on the Scala mailing list. Quoting Lukas Rytz:
Also note that in 2.8.0 the syntax for java annotations will no longer use the name-value
pairs but named arguments instead, i.e.
#ann{ val x = 1, val y = 2} ==> #ann(x = 1, y = 2)
The way scala deals with attributes is a little funky. I think what you're trying to do should be expressed like this:
#Test { val expected = classOf[ NullPointerException] }
def someTest {
// test code
}
Scala language page with many annotation examples.
This works for me (JUnit 4.10, Scala 2.10.2):
#Test(expected = classOf[NullPointerException])
def testFoo() {
foo(null)
}
Similar to what Tristan suggested, but this syntax actually compiles and works in my project.
Edit: Uh, looking closer, this is exactly what the original question had. Well, I guess having the latest working syntax also in answers doesn't hurt.
You can also try specs with:
class mySpec extends SpecificationWithJUnit {
"this expects an exception" in {
myCode must throwA[NullPointerException]
}
}
Eric.
Use ScalaTest and JUnit together and you can do:
import org.scalatest.junit.JUnitSuite
import org.scalatest.junit.ShouldMatchersForJUnit
import org.junit.Test
class ExampleSuite extends JUnitSuite with ShouldMatchersForJUnit {
#Test def toTest() {
evaluating { "yo".charAt(-1) } should produce [StringIndexOutOfBoundsException]
}
}