Evaluating a GROOVY expression while debugging - eclipse

I'm trying to debug a simple groovy project in eclipse, code is as simple as this:
def list = [1, 2, 3, 4, 5]
println list.collect { it + 1 }
And it executes fine; only when I try to evaluate this part:
list.collect { it + 1 }
in the display view (or inspect it in the editor: shift+crl+i) I'm shot at with the following message:
list.collect { it + 1 }
Evaluation failed. Reason(s):
org.codehaus.groovy.runtime.InvokerInvocationException (id=115)
Anyone ever had this issue, and knows how to fix it? Thanks a ton.
Using STS 2.5.2 (Eclipse 3.6.1r361), Groovy 1.7.8, jdk1.6.0_24; Groovy-Eclipse Plugin 2.1.2.xx.20110218
And btw, I think the problem didn't occur back when I was using sts 2.3.x (eclipse 3.5.x)

You cannot create closures in the display view. Instead, you will need to write this out in a for loop. Eg-
def newList = []
for (elt in list) {
newList << elt++
}
print newList
This is a vm limitation since under the hood, a closure is represented by a class declaration. There is no easy way to inject a class generated by the display view into the running application.

Related

IntelliJ breakpoint in scala foreach not working

I'm using IntelliJ IDEA Ultimate 16.1.2 and Scala 12. When setting breakpoints in foreach loops, they don't get hit.
Breakpoints above the foreach work and get the tick in the breakpoint (valid breakpoint) but the ones in the foreach don't get the tick and the program doesn't break there either.
I tried invalidating the IntelliJ Cash, restarting my PC and IntelliJ, rebuilding maven - nothing worked.
This are the VM parameters I'm using, but I've also tried it without any, which didn't help:
-XX:+UnlockCommercialFeatures
-XX:+FlightRecorder
-Dcom.sun.management.jmxremote
-XX:StartFlightRecording=filename=recording.jfr
-server
-Xms1G
-Xmx4G
-XX:+UseG1GC
-XX:+UseStringDeduplication
Thanks for your help!
Here is my code:
class RunTestCasesAction extends AbstractAction {
def actionPerformed(e: ActionEvent) = {
val parent = methodToGetParentComponent() //breakpoint works
getFileName(parent).foreach { testFileName =>
val dialog = new SomeDialog() // breakpoint doesn't work
}
}
private def getFileName(parent: Component): Option[String] = {
val baseDir = getExportDir
val fc = new JFileChooser(baseDir)
val rc = fc.showDialog(null, "Select test file")
if (rc == JFileChooser.APPROVE_OPTION) Some(fc.getSelectedFile.toString) else None
}
What you are doing is creating new objects and assigning them inside a foreach loop.
This has no effect on other part on the projects.
Compiler optimizes your code and this way this code block is never executed. This val dialog = new SomeDialog() are created inside foreach and this objects are immediatelly destroyed, cause their scope is only inside foreach loop, so there is no point of doing it so.
If you want to go inside the loop, put there something what matters, what will be reusable. Eg. you can collect this objects.
Make sure compiler will not optimize your code this way.
Probably you could try to use some compiler optimizations flags, but I am not sure about that.
Here are informations on how debuggers work.

Visual Debugging Helper - POST, variables, etc ( within Controllers in Play Framework )

I'm curious if there is already existing library that I'm not aware of, for visual representation of request, or any other variables within Play Framework.
For example, in Python - it's possible to use pprint:
https://docs.python.org/2/library/pprint.html
Another example, in PHP - there is a var_dump or something like Kint:
http://raveren.github.io/kint/
To give a little bit more context of where it would be used - Controller (in this example I assume that fictional scala_or_play_visual_dump would either return or exit further execution):
def displaySomething = Action {
val x = List(1, 2, 3)
// ??? - scala_or_play_visual_dump(x)
Ok("This code shouldn't be executed...")
}
and output (in a browser!, not log files) will be something like either Jupyter notebook produces, or pprint, or var_dump or Kint tool/library:
List[Int] = List(1, 2, 3)

scala reassignment to val in Option Class

My code looks like:
case class SRecord(trialId: String, private var _max:Int) {
def max=_max
def max_=(value:Int):Unit=_max=value
}
Then later on I apply a function onto it:
def groupSummaryRecords(it:Iterator[Option[SRecord]], optionSummary:Option[SRecord]):Option[SRecord] = {
var max=0;
var sRecord1 : Option[SRecord] = None
var i=0
while(it.hasNext) {
var sRecord:Option[SRecord] = it.next();
if(i==0) {
sRecord1 = sRecord;
}
..
}
sRecord1.max=max; // getting 'reassignment to val' compilation error
..
}
Why am i getting this compilation error, and how to fix it ?
If I instead change sRecord and sRecord1 instances to be of type SRecord instead of Option[SRecord] as well as the method signature, it all works fine however.
But in some cases I may have a null SRecord hence the use of None/Some. I am new to Scala, using Option/Some all over feels like a real pain if you ask me, i am just thinking of removing all this Option nonsense and testing for 'null' in good ol' Java, at least my code would work ??!
With the line sRecord1.max=max you are trying to call the max method on an Option[SRecord], not an SRecord. You want to access the contained SRecord (if any) and call the method on that, which can be done using foreach:
sRecord1.foreach(_.max=max)
which is desugared to:
sRecord1.foreach( srec => srec.max=max )
(the actual name "srec" is made up, the compiler will assign some internal name, but you get the idea). If sRecord1 is None, this won't do anything, but if it is Some(srec), the method execution will be passed in to operate on the contained instance.

Entity Framework and Nested Lambda Expressions

I've just started using Lambda expressions, and really like the shortcut. I also like the fact that I have scope within the lambda of the encompassing method. One thing I am having trouble with is nesting lambdas. Here is what I am trying to do:
public void DoSomeWork()
{
MyContext context = new MyDomainContext();
context.GetDocumentTypeCount(ci.CustomerId, io =>
{
if (io.HasError)
{
// Handle error
}
// Do some work here
// ...
// make DB call to get data
EntityQuery<AppliedGlobalFilter> query =
from a in context.GetAppliedGlobalFiltersQuery()
where a.CustomerId == ci.CustomerId && a.FilterId == 1
select a;
context.Load<AppliedGlobalFilter>(query, lo =>
{
if (lo.HasError)
{
}
**// Do more work in this nested lambda.
// Get compile time error here**
}
}, null);
}, null);
}
The second lambda is where I get the following compile time error:
Cannot convert Lambda expression to type 'System.ServiceModel.DomainService.Client.LoadBehavior' because it is not a delegate type
The compiler is choosing the wrong overload for the Load method even though I am using the same override I did in the previous Lambda.
Is this because I am trying to nest? Or do I have something else wrong?
Thanks,
-Scott
Found the problem as described in my comment above. I'll head back to work now - red face and all....
I realize this is not the answer you want, but I suggest caution about lengthy and/or nested lambdas. They work, but they often make code harder to read / maintain by other developers. I try to limit my lambdas in length to three statements, with no nesting.

Scala problem with jMock expectations and returning a value from mock

Solved. IntelliJ didn't highlight the fact that my imports were incomplete.
Hi,
I have a simple Scala program that I'm trying to develop using jMock. Setting basic expectations works nicely but for some reason Scala does not understand my attempt to return a value from a mock object. My maven build spews out the following error
TestLocalCollector.scala:45: error: not found: value returnValue
one (nodeCtx).getParameter("FilenameRegex"); will( returnValue(regex))
^
And the respective code snippets are
#Before def setUp() : Unit = { nodeCtx = context.mock(classOf[NodeContext]) }
...
// the value to be returned
val regex = ".*\\.data"
...
// setting the expectations
one (nodeCtx).getParameter("FilenameRegex"); will( returnValue(regex))
To me it sounds that Scala is expecting that the static jMock method returnValue would be a val? What am I missing here?
Are you sure about the ';'?
one (nodeCtx).getParameter("FilenameRegex") will( returnValue(regex))
might work better.
In this example you see a line like:
expect {
one(blogger).todayPosts will returnValue(List(Post("...")))
}
with the following comment:
Specify what the return value should be in the same expression by defining "will" as Scala infix operator.
In the Java equivalent we would have to make a separate method call (which our favorite IDE may insist on putting on the next line!)
one(blogger).todayPosts; will(returnValue(List(Post("..."))))
^
|
-- semicolon only in the *Java* version
The OP explains it himself:
the returnValue static method was not visible, thus the errors.
And the will method just records an action on the latest mock operation, that's why it can be on the next line or after the semicolon :)
import org.jmock.Expectations
import org.jmock.Expectations._
...
context.checking(
new Expectations {
{ oneOf (nodeCtx).getParameter("FilenameRegex") will( returnValue(".*\\.data") ) }
}
)