How do you write an empty while loop in Coffeescript? - coffeescript

I'm trying to translate some old code to Coffeescript. But there is no direct translation for:
while ( doWork() ) {}
"while doWork()" with nothing after it results in a syntax error.

while doWork() then
Should do the trick

using then is probably the canonical solution since it is explicitly meant for separating the condition from the (in this case empty) body. Alternatively you can write
while doWork()
;#
(the # keeps vim syntax highlighting from flagging it as an error)
I also like the continue while doWork() solution, but I strongly advise against any other form of expression while doWork() mentioned in the comments since when this is the last statement of a function it will become a list constructor:
_results = [];
while (doWork()) {
_results.push(expression);
}
return _results;

Related

Does Flutter have an equivalent command to Python's `pass` keyword?

All I need to do with my code is if it passes the if statement, it simply passes the class and moves on to the rest of the code, but in my research, I can't exactly figure out what the command may be. Is there a way to implement Python's pass keyword in dart?
There is no direct equivalent to the pass statement in Dart language. In Python, there are language restrictions that do not allow leaving empty loops, if statements and so on. However, in Dart it's completely OK to do that, you can just leave empty braces. For instance:
void main() {
for (int i = 0; i < 5; i++) {
// Ignored
}
try {
// Some logic
} on Exception {
// Ignored
}
if (true) {
// Ignored
}
}
There are even some lint rules that check for you not to leave empty logic (you can still add a comment and not leave them empty, though): empty_statements, empty_catches and so on.
Just add empty curly braces {}. For example:
const num = 5;
if (num == 5) {
}
you don't have to provide code within the curly braces, it can be left empty.

How to call functions inside ternary operators in UnityScript?

I'm trying to decide which function to call, based on a boolean value.
myBooleanVariable ? function1() : function2();
Unity gives the error :
Expressions in statements must only be executed for their
side-effects.
So why does this not work, and how can I make it work ?
Thanks for any help !
So why does this not work, and how can I make it work ?
If it's true that it doesn't work (I don't have Unity to hand), it means UnityScript (Unity's implementation of JavaScript) doesn't support the expression statement. Which puts it at variance with the specification, and means a fair number of JavaScript idioms won't work in it. Your line is perfectly valid JavaScript/ECMAScript. You might check to see if there are "lint"-style options you can enable/disable.
The solution would be to use the result of the expression, or rewrite that using if.
Use the result:
var f = myBooleanVariable ? function1() : function2();
Using if:
if (myBooleanVariable) {
function1();
}
else {
function2();
}
Or if you really want the if to be on one line:
if (myBooleanVariable) function1(); else function2();

How to check for null in a single statement in scala?

In my scala code:
QueueManager.add(getObject)
where getObject is a method that returns an object of type QueueObject.
def getObject : QueuObject = {
val response = //some response
return response
}
Is there a way I can check for the response being null, while adding the QueueObject? I know I can do this:
if (getObject != null)
QueueManager.add(getObject)
But I do not wish to add a level of indentation. Is there an operator that does that inline?
Thanks.
Try to avoid using null in Scala. It's really there only for interoperability with Java. In Scala, use Option for things that might be empty. If you're calling a Java API method that might return null, wrap it in an Option immediately.
def getObject : Option[QueueObject] = {
// Wrap the Java result in an Option (this will become a Some or a None)
Option(someJavaObject.getResponse)
}
Note: You don't need to put it in a val or use an explicit
return statement in Scala; the result will be the value of
the last expression in the block (in fact, since there's only one statement, you don't even need a block).
def getObject : Option[QueueObject] = Option(someJavaObject.getResponse)
Besides what the others have already shown (for example calling foreach on the Option, which might be slightly confusing), you could also call map on it (and ignore the result of the map operation if you don't need it):
getObject map QueueManager.add
This will do nothing if the Option is a None, and call QueueManager.add if it is a Some.
I find using a regular if however clearer and simpler than using any of these "tricks" just to avoid an indentation level. You could also just write it on one line:
if (getObject.isDefined) QueueManager.add(getObject.get)
or, if you want to deal with null instead of using Option:
if (getObject != null) QueueManager.add(getObject)
edit - Ben is right, be careful to not call getObject more than once if it has side-effects; better write it like this:
val result = getObject
if (result.isDefined) QueueManager.add(result.get)
or:
val result = getObject
if (result != null) QueueManager.add(result)
Option(getObject) foreach (QueueManager add)
If it instead returned Option[QueueObject] you could use a construct like getObject.foreach { QueueManager.add }. You can wrap it right inline with Option(getObject).foreach ... because Option[QueueObject](null) is None.
Although I'm sure #Ben Jackson's asnwer with Option(getObject).foreach is the preferred way of doing it, I like to use an AnyRef pimp that allows me to write:
getObject ifNotNull ( QueueManager.add(_) )
I find it reads better.
And, in a more general way, I sometimes write
val returnVal = getObject ifNotNull { obj =>
returnSomethingFrom(obj)
} otherwise {
returnSomethingElse
}
... replacing ifNotNull with ifSome if I'm dealing with an Option. I find it clearer than first wrapping in an option and then pattern-matching it.
(For the implementation, see Implementing ifTrue, ifFalse, ifSome, ifNone, etc. in Scala to avoid if(...) and simple pattern matching and the Otherwise0/Otherwise1 classes.)

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.

; expected but <place your favourite keyword here> found

I'm trying to write a class for a scala project and I get this error in multiple places with keywords such as class, def, while.
It happens in places like this:
var continue = true
while (continue) {
[..]
}
And I'm sure the error is not there since when I isolate that code in another class it doesn't give me any error.
Could you please give me a rule of thumb for such errors? Where should I find them? are there some common syntactic errors elsewhere when this happens?
It sounds like you're using reserved keywords as variable names. "Continue", for instance, is a Java keyword.
You probably don't have parentheses or braces matched somewhere, and the compiler can't tell until it hits a structure that looks like the one you showed.
The other possibility is that Scala sometimes has trouble distinguishing between the end of a statement with a new one on the next line, and a multi-line statement. In that case, just drop the ; at the end of the first line and see if the compiler's happy. (This doesn't seem like it fits your case, as Scala should be able to tell that nothing should come after true, and that you're done assigning a variable.)
Can you let us know what this code is inside? Scala expects "expressions" i.e. things that resolve to a particular value/type. In the case of "var continue = true", this does not evaluate to a value, so it cannot be at the end of an expression (i.e. inside an if-expression or match-expression or function block).
i.e.
def foo() = {
var continue = true
while (continue) {
[..]
}
}
This is a problem, as the function block is an expression and needs to have an (ignored?) return value, i.e.
def foo() = {
var continue = true
while (continue) {
[..]
}
()
}
() => a value representing the "Unit" type.
I get this error when I forget to put an = sign after a function definition:
def function(val: String):Boolean {
// Some stuff
}