difference between 'def' and no 'def' - function

I am a groovy beginner.
I am confused that whether 'def' is used.
def str = "hello"
print str
vs
str = "hello"
print str
From this example. the result is same.But I wonder if they are different.
And are there other situations are different?

Second example is only valid if you are working with scripts. See 3.2 Script class here.
Without def variable is stored in Script's binding, and works as a "global" variable in that script.
If you define variable with def it will be a local variable of Script's run method, and follow all rules of local variable. This difference doesn't really matter if you work with one script.
Difference can be illustrated with following snippet:
def closureA = { println(a) }
def closureB = { println(b) }
a = "I'm global"
def b = "I'm local"
println(a) // prints "I'm global"
println(b) // prints "I'm local"
closureA() // prints "I'm global"
closureB() // throws groovy.lang.MissingPropertyException: No such property: b
Here I first declare 2 closures (anonymous functions). Note, that at declaration time neither a nor b is declared, and therefore not accessible for closures. It's fine.
Then I call println directly after declaration, and in that case I'm in the same scope with both a and b. I'm able to print their value.
Next I call closures. Both closure check local scope, and if variable is not found there, they check bindings. And here is the difference: a is accessible, while b - not.

Related

How to get template function from so/dll?

How to get template function from so/dll?
I tried:
Library libdll;
T abc(T)();
static this()
{
libdll = Library("libs/libdll.so");
abc = cast(typeof(abc)) libdll.loadSymbol!(typeof(abc))("dll.abc");
//abc();
}
But then the type of abc is determined as void.
I get error in the compilation:
Error: expression `cast(void)dlsym(this.handle, toStringz(cast(const(char)[])m))` is `void` and has no value
m - is the mangled name of dll.abc.
Templates in D are a compile-time-only construct, and don't exist in sos/dlls. Specific instances end up in the so, but only those that are used there. In other words, if you have this code in the so/dll:
module dll;
T abc(T)() {
T result = void;
return result;
}
void use() {
auto var = abc!int();
}
You should be able to get dll.abc!int.abc (mangled name _D3dll__T3abcTiZQhFNaNbNiNfZi) from the so/dll.
If you want to call abc with some other type, like abc!string, you're out of luck - the code just doesn't exist.
That covers the feasibility. If you only want a specific instance you know has been instantiated, there's another issue at work here, which is the use of typeof(abc). Again, abc is a compile-time thing, and doesn't have a type. The compiler, confusingly, returns void for typeof(abc), giving you the error message is `void` and has no value.
abc!int is a function, and does have a type (pure nothrow #nogc #safe int()), so using that should work. As hinted at above, the name would be dll.abc!int.abc (it's an eponymous template, hence the repeated name).
TL;DR: If you want a specific instance of the template, and that has been instantiated in the so/dll, this code should work (but has not been tested):
Library libdll;
T abc(T)();
static this()
{
libdll = Library("libs/libdll.so");
abc = cast(typeof(abc!int)) libdll.loadSymbol!(typeof(abc!int))("dll.abc!int.abc");
abc();
}

Chapel : Understanding lifetime of managed classes with zip and user-defined iterators

I'm trying to understand the lifetime of an owned class, when being used in a user-defined iterator. Consider the following code :
var a = new owned C();
var b = new owned C();
a.i = 2;
forall (a1,b1) in zip(a,b) {
b1 = a1;
}
forall (a1,b1) in zip(a,b) {
writeln(a1, " ",b1);
}
class C {
var i : int;
iter these() {
yield 1;
}
iter these(param tag : iterKind) where tag==iterKind.leader {
yield 1;
}
iter these(param tag : iterKind, followThis) ref
where tag==iterKind.follower {
yield i;
}
}
Compiling and running this code gives the following error
(08:54)$ chpl test.chpl --warn-unstable
(08:54)$ ./test
test.chpl:25: error: attempt to dereference nil
(08:54)$ chpl --version
chpl version 1.19.0 pre-release (2c10dbe)
It isn't clear to me when the class is being deinit-ed here. If I replace the owned with a shared, this example works as expected. More interestingly, changing the first loop to
forall (a1,b1) in zip(a.borrow(),b.borrow()) {
allows the code to work as well. In what cases is an argument automatically coerced into a borrowed instance?
I'm pretty sure this is a bug. I'll have a look.
In what cases is an argument automatically coerced into a borrowed instance?
Right now, when:
when calling a method on it (the this argument will be a borrow)
when passing to an argument of type C or borrowed C (which mean the same).
when passing to a totally generic function argument.
I'm not sure if we're going to keep rule 3 or not. But that's not the problem in your case - rather the problem is that some compiler-introduced code implementing the forall statement taking away the owned value. That's a bug.

Advanced Parameterization Manual in Chisel

This is inside the chisel library
object Module {
// returns a new Module of type T, initialized with a Parameters instance if _p !=None.
def apply[T<:Module](c: =>T)(implicit _p: Option[Parameters] = None):T
}
I don't understand the =sign in the parameters. What does it represents?
The = in (implicit _p: Option[Parameters] = None) is assigning a default value of None to the parameter _p. That means that unless the otherwise specified there is no Parameter instance assigned to _p.
Just in case you are asking about the => in (c: =>T), the => is means that the first parameter c is a reference to a function that returns an instance of T, where T is a subclass of Module.
There's a bunch of idiomatic features of Scala being employed here: Function Currying, implicit parameters, Functions as first class citizens of the language. It's worth a taking a bit of time to learn the syntax of these things. Check out Chisel's generator-bootcamp tutorial particularly section 3.2 and 3.3 for some of the ways Chisel takes advantage of Scala's syntax
This example has two = signs. The first corresponds to By-name parameters: https://docs.scala-lang.org/tour/by-name-parameters.html.
The former is important because Modules in Chisel must wrapped in Module(...) when they are constructed. We generally accomplish using call by-name:
class MyModule extends Module {
...
}
// This works!
def func(mod: => MyModule) = {
val instance = Module(mod) // The module is constructed inside Module(...)
}
func(new MyModule)
// This doesn't work!
def func(mod: MyModule) = {
val instance = Module(mod)
}
func(new MyModule) // The module is constructed too early, here!
The second is a Default parameter: https://docs.scala-lang.org/tour/default-parameter-values.html. It's mainly a convenience thing:
def func(x: Int = 3) = { println(x) }
func(5) // prints 5
func() // prints 3

Spock mock returns null inside collabolator but not in feature method

I have a problem with Spock Mock() object.
I have a java class I'm trying to test. This class does some ftp stuff I want to mock.
My sample code
class ReceiveDataTest extends Specification{
String downloadPath = 'downloadPath';
String downloadRegex = 'downloadRegex';
SftpUtils sftpUtils = Mock();
ReceiveData receiveData;
def setup(){
sftpUtils.getFileNames(downloadPath,downloadRegex) >> ['file1', 'file2']
receiveData= new ReceiveData()
receiveData.setDownloadPath(downloadPath)
receiveData.setDownloadRegex(downloadRegex)
receiveData.setSftpUtils(sftpUtils);
}
def "test execute"() {
given:
def files = sftpUtils.getFileNames(downloadPath,downloadRegex)
files.each{println it}
when:
receiveData.execute();
then:
1*sftpUtils.getFileNames(downloadPath,downloadRegex)
}
}
public class ReceiveData(){
//fields, setters etc
public void execute() {
List<String> fileNames = sftpUtils.getFileNames(downloadPath, downloadRegex);
for (String name : fileNames) {
//dowload and process logic
}
}
}
Now, inside "test execute" the files.each{} prints what is expected. But when receiveData.execute() is called my sftpUtils are returning null..
Any ideas why?
EDIT
Maybe i didnt state my problem well - that I dont want to just check if getFileNames was called. I need the result to proper check the for loop. If I comment the loop inside execute, the test passes. But since I use the result of the getFilenames() method, I get a NPE execute method reaches the for loop. With mockito I would do something like this
Mockito.when(sftpUtils.getFilenames(downloadPath, downloadRegex)).thenReturn(filenamesList);
receiveData.execute();
Mockito.verify(sftpUtils).getFilenames(downloadPath, downloadRegex);
//this is what I want to test and resides inside for loop
Mockito.verify(sftpUtils).download(downloadPath, filenamesList.get(0));
Mockito.verify(sftpUtils).delete(downloadPath, filenamesList.get(0));
but I cannot use Mockito.verify() inside Spock then block
The main problem is that you did not include the response generator (the >> part) in the expectation (i.e. the "1 * ..." part inside the then: block).
This is explained well in the spock documentation.
http://spockframework.org/spock/docs/1.0/interaction_based_testing.html#_combining_mocking_and_stubbing
https://spock-framework.readthedocs.org/en/latest/interaction_based_testing.html#wheretodeclareinteractions
You shouldn't have to declare your stub in the setup: block. You can just specifiy it once in the then: block -- even though that follows the call to receiveData.execute(). That's part of the magic of spock thanks to Groovy AST transformations. And since (non-shared) fields are reinitialized before each test (more AST based magic), you don't even need setup() in this case.
Another odd thing is that you are both stubbing out sftpUtils.getFilenames() and also calling it from the test code. Mocks and stubs are intended to replace collaborators that are called from the system under test. There's no reason to call the stub from the test driver. So delete the call to getFilenames() from your given block and let the code under test call it instead (as it does).
Groovy lets you simplify calls to Java set and get methods. Look at the initialization of receiveData below. Its okay to use def in Groovy. Let the compiler figure out the data types for you.
Leading to something like:
class ReceiveDataTest extends Specification {
// only use static for constants with spock
static String PATH = 'downloadPath'
static String REGEX = 'downloadRegex'
def mockSftpUtils = Mock(SftpUtils)
def receiveData = new ReceiveData(downloadPath : PATH,
downloadRegex : REGEX,
sftpUtils : mockSftpUtils)
def "execute() calls getFileNames() exactly once"() {
when:
receiveData.execute()
then:
1 * mockSftpUtils.getFileNames(PATH, REGEX) >> ['file1', 'file2']
0 * mockSftpUtils.getFileNames(_,_)
// The second line asserts that getFileNames() is never called
// with any arguments other than PATH and REGEX, aka strict mocking
// Order matters! If you swap the lines, the more specific rule would never match
}
}

Scala: val foo = (arg: Type) => {...} vs. def(arg:Type) = {...}

Related to this thread
I am still unclear on the distinction between these 2 definitions:
val foo = (arg: Type) => {...}
def(arg:Type) = {...}
As I understand it:
1) the val version is bound once, at compile time
a single Function1 instance is created
can be passed as a method parameter
2) the def version is bound anew on each call
new method instance created per call.
If the above is true, then why would one ever choose the def version in cases where the operation(s) to perform are not dependent on runtime state?
For example, in a servlet environment you might want to get the ip address of the connecting client; in this case you need to use a def as, of course there is no connected client at compile time.
On the other hand you often know, at compile time, the operations to perform, and can go with immutable val foo = (i: Type) => {...}
As a rule of thumb then, should one only use defs when there is a runtime state dependency?
Thanks for clarifying
I'm not entirely clear on what you mean by runtime state dependency. Both vals and defs can close over their lexical scope and are hence unlimited in this way. So what are the differences between methods (defs) and functions (as vals) in Scala (which has been asked and answered before)?
You can parameterize a def
For example:
object List {
def empty[A]: List[A] = Nil //type parameter alllowed here
val Empty: List[Nothing] = Nil //cannot create a type parameter
}
I can then call:
List.empty[Int]
But I would have to use:
List.Empty: List[Int]
But of course there are other reasons as well. Such as:
A def is a method at the JVM level
If I were to use the piece of code:
trades filter isEuropean
I could choose a declaration of isEuropean as either:
val isEuropean = (_ : Trade).country.region = Europe
Or
def isEuropean(t: Trade) = t.country.region = Europe
The latter avoids creating an object (for the function instance) at the point of declaration but not at the point of use. Scala is creating a function instance for the method declaration at the point of use. It is clearer if I had used the _ syntax.
However, in the following piece of code:
val b = isEuropean(t)
...if isEuropean is declared a def, no such object is being created and hence the code may be more performant (if used in very tight loops where every last nanosecond is of critical value)