Whats the ScalaJS way to make an event occur in n milliseconds time? - scala.js

Is it to use ScalaJS DOM and use the following?
org.scalajs.dom.setTimeout( () => {
// Work
}, 1000)
Is there another way or a better way within the context of ScalaJS?

Starting with Scala.js 0.6.0, there is a more standard way, and more idiomatic Scala, to do it:
import scala.scalajs.js.timers._
setTimeout(1000) { // note the absence of () =>
// work
}
See the ScalaDoc of timers.

There isn't a better way. If you want you can wrap it in a helper and call it whatever you want, but by default that's it.

Related

What does the #suspendable annotation in Scala do?

While reading the Scala.React implementation on GitHub I've stumbled across the #suspendable annotation:
object Reactor {
def loop[A](op: FlowOps => Unit #suspendable): Reactor = new Reactor {
def body = while (!isDisposed) op(this)
}
}
In the paper Deprecating the Observer Pattern with Scala.React, the Reactor object is used in the following way:
Reactor.loop { self =>
// step 1
val path = new Path((self await mouseDown).position)
self.loopUntil(mouseUp) { // step 2
path.lineTo(m.position)
draw(path)
}
path.close() // step 3
draw(path)
}
Notably, the code in the Reactor body can wait for Events, like mouseDown. Therefore it looks like the code is executed asynchronously, even though there is no explicit use of threads. Because I couldn't find what the #suspandable annotation does, I feel like I'd need to understand it, before I can understand the rest of the implementation. Therefore:
What does the #suspendable annotation do?
Are there scenarios, where it is required?
When would I use it?
My suspicion is, that it somehow abstracts over, and allows for asynchronous execution. If that is true:
How does it work "under the hood" / how is it implemented?
#suspendable is an annotation introduced by the now-abandoned Scala Continuations library (which for a while was part of the Scala standard library) and used by the associated compiler plugin.
The project explored adding delimited continuations to Scala, and about the best extant documentation for it is in the doc-comments here. #suspendable is an alias for #cps[Unit], which basically signals the compiler plugin to perform a CPS transform at shifts when it's called within a reset block.
A rough idea of what the plugin does is:
def five(): Int #cps[Int] = shift { k: (Int => Int) => k(5) }
reset { five() + 1 }
ultimately gets translated to something as simple as
val kont: Int => Int = _ + 1
five(kont)
The basic idea is to translate the remainder of the expression into a function which takes the result up to that point as an argument and pass it into a function which will calculate the result up to that point and call the function representing the remainder of the expression. This is basically what you do manually when using a callback-based API (e.g. in Node.js).
The Future APIs (as well as the async/await compiler plugins for working with Futures) simplified and the use of CPS for asynchronous programming (which is, outside of writing compilers, the only wide non-academic use of CPS) as well as adding more intuitive support for concurrency and asynchrony, which led to the deprecation and removal of continuation support.
This is part of the deprecated scala-continuations library.
You can find documentation for it at this URL:
https://www.scala-lang.org/files/archive/api/2.11.12/scala-continuations-library/#scala.util.continuations.package

Is a while loop already implemented with pass-by-name parameters? : Scala

The Scala Tour Of Scala docs explain pass-by-name parameters using a whileLoop function as an example.
def whileLoop(condition: => Boolean)(body: => Unit): Unit =
if (condition) {
body
whileLoop(condition)(body)
}
var i = 2
whileLoop (i > 0) {
println(i)
i -= 1
} // prints 2 1
The section explains that if the condition is not met then the body is not evaluated, thus improving performance by not evaluating a body of code that isn't being used.
Does Scala's implementation of while already use pass-by-name parameters?
If there's a reason or specific cases where it's not possible for the implementation to use pass-by-name parameters, please explain to me, I haven't been able to find any information on it so far.
EDIT: As per Valy Dia's (https://stackoverflow.com/users/5826349/valy-dia) answer, I would like to add another question...
Would a method implementation of the while statement perform better than the statement itself if it's possible not to evaluate the body at all for certain cases? If so, why use the while statement at all?
I will try to test this, but I'm new to Scala so it might take me some time. If someone would like to explain, that would be great.
Cheers!
The while statement is not a method, so the terminology by-name parameter is not really relevant... Having said so the while statement has the following structure:
while(condition){
body
}
where the condition is repeatedly evaluated and the body is evaluated only upon the condition being verified, as show this small examples:
scala> while(false){ throw new Exception("Boom") }
// Does nothing
scala> while(true){ throw new Exception("Boom") }
// java.lang.Exception: Boom
scala> while(throw new Exception("boom")){ println("hello") }
// java.lang.Exception: Boom
Would a method implementation of the while statement perform better than the statement itself if it's possible not to evaluate the body at all for certain cases?
No. The built-in while also does not evaluate the body at all unless it has to, and it is going to compile to much more efficient code (because it does not need to introduce the "thunks"/closures/lambdas/anonymous functions that are used to implement "pass-by-name" under the hood).
The example in the book was just showing how you could implement it with functions if there was no built-in while statement.
I assumed that they were also inferring that the while statement's body will be evaluated whether or not the condition was met
No, that would make the built-in while totally useless. That is not what they were driving at. They wanted to say that you can do this kind of thing with "call-by-name" (as opposed to "call-by-value", not as opposed to what the while loop does -- because the latter also works like that).
The main takeaway is that you can build something that looks like a control structure in Scala, because you have syntactic sugar like "call-by-name" and "last argument group taking a function can be called with a block".

How can I allow the caller to call method of field of case class?

I am not sure the keywords for this pattern, sorry if the question is not clear.
If you have:
case class MyFancyWrapper(
somethingElse: Any,
heavyComplexObject: CrazyThing
)
val w = MyFancyWrapper(???, complexThing)
I want to be able to call w.method with the method coming from complexThing. I tried to extends CrazyThing but it is a trait and I don't want to implement all the method that would be very tedious. I also don't want to have to do:
def method1 = heavyComplexObject.method1
...
for all of them.
Any solution ?
Thanks.
You can do this with macros but I agree with Luis that this is an overkill. Macros are intended to repetitive boring things, not one time boring things. Also this is not as trivial as it sounds, because you probably don't want to pass through all the methods (you probably still want your own hashCode and equals). Finally macros have bad IDE support so most probably no auto-completion for all those methods. On the other hand if you do use a good IDE (like IDEA) there is most probably an action like "Delegate methods" that will generate most of the code for you. You still will have to change the return type from Unit to MyFancyWrapper and add returning this at the end of each method but this can easily be done with mass replace operations (hint: replace "}" with "this }" and the automatically re-formatting code should do the trick)
Here are some screenshots of the process from JetBrains IDEA:
You can use an implicit conversion to make all the methods of heavyComplexThing directly available on MyFancyWrapper:
implicit def toHeavy(fancy: MyFancyWrapper): CrazyThing = fancy.heavyComplexObject
This needs to be in scope when the method is called.
In the comments you indicate that you want to return this so that you can chain multiple calls on the same object:
w.method1.method2.method3
Don't do this
While this is a common pattern in non-functional languages, it is bad practice is Scala for two reasons:
This pattern inherently relies on side-effects, which is the antithesis of functional programming.
It is confusing, because in Scala chaining calls in this way is used to implement a data pipeline, where the output of one function is passed as the input to the next.
It is much clearer to write separate statements so that it is obvious that the methods are being called on the same object:
w.method1()
w.method2()
w.method3()
(It is also conventional to use () when calling methods with side effects)

Idiomatic way to handle a stream end with RxJS

I need to do a some action when stream ends. What the idiomatic way to do that?
Now I use the code bellow:
source.subscribe(undefined, undefined, function() {
socket.send({type: 'end'});
});
There are several ways to accomplish this:
Use the operator subscribeOnCompleted() instead of passing in empty values to the .subscribe method.
Use tapOnCompleted(), same as above, but it won't start the sequence and you can inject it part way through the sequence.
Use the .finally() which will get executed when the sequence finishes (normally or otherwise).
In your example you are showing a side effect but if you were doing clean up of resources it would be more semantic to use .using() which takes a disposable and ties it to the lifetime of the subscription.
In order these look like:
source.subscribeOnCompleted(() => socket.send({type: 'end'}));
source.tapOnCompleted(() => socket.send({type: 'end'})).subscribe()
source.finally(() => socket.send({type: 'end'})).subscribe()
Rx.Observable.using(() => createResource(), (resource) => source).subscribe()

scala: alias for a keyword?

is there a way to create an alias for a scala keyword? in particular i have some boilerplate syntax that involves "val" and in order to make it easier to read i'd like to be able to type something "##" instead and have that translated to val.
Edit:
In some cases, it might be very convenient to be able to replace "lazy val", not just "val". The use case has to do with a function that acts as a python decorator. It looks like this:
lazy val function = Decorate(function_ _)
def function_(x: Int, ...) = { ... }
it would be a lot nicer if it looked like this:
# function = Decorate(function_ _)
def function_(x: Int, ...) = { ... }
just so that there's not a val stacked on top of a def, where both names are extremely similar. (the function_ name is not meant to be called, so it's the cleanest to make the names similar.)
No, there isn't.
(filler so SO will let me post)
Ouch! This isn't particularly idiomatic Scala.
To start with, you're naming a method "function_", they're not the same thing, a method is simply a member of some class, a Function is an object in its own right (although a method can be "lifted" to a function by the compiler, in a similar fashion to the autoboxing of primitives).
Second, what is Decorate? The initial uppercase letter suggests that it's a singleton, therefore an object and the only actual "Function" in that expression!
Could you post a bit more info as to what the method and decorator actually do, so that I can give you a better example as to how you might achieve the same in Scala?
I guess one could write a Scala Compiler Plugin to achieve this. At least the Eclipse Plugin actually uses the original Scala Compiler, so it might actually work nicely with the IDE.
Other then that: Daniel C. Sobral is correct: No, there isn't.
Still it sounds like a lot of trouble for a little gain.
If function_ is never meant to be called directly, why not write
lazy val function = Decorate { (x: Int, ...) => ... }
or even
/**
* This version makes it more explicit that it's a function value.
*/
lazy val function: (Int, ...) => ReturnType =
Decorate { (x, ...) => ... }
Some caution is advised: conciseness and terseness are two different things. Here, it looks like you're trying to buy a few keystrokes at a very high price in terms of readability.
Update:
If you really want to achieve a simpler syntax for this sort of thing, you will need a compiler plugin. If you're going to go that far, I'd suggest using an annotations-based syntax that's likely to be pretty intuitive for Java/Scala developers:
#decorate(Memoize)
def slowFn(i: Int) = { ... }