Dynamic Proxy using Scalas new Dynamic Type - scala

Is it possible to create an AOP like interceptor using Scalas new Dynamic Type feature? For example: Would it be possible to create a generic stopwatch interceptor that could be mixed in with arbitrary types to profile my code? Or would I still have to use AspectJ?

I'm pretty sure Dynamic is only used when the object you're selecting on doesn't already have what you're selecting:
From the nightly scaladoc:
Instances x of this trait allow calls x.meth(args) for arbitrary method names meth and argument lists args. If a call is not natively supported by x, it is rewritten to x.invokeDynamic("meth", args)
Note that since the documentation was written, the method has been renamed applyDynamic.

No.
In order for a dynamic object to be supplied as a parameter, it'll need to have the expected type - which means inheriting from the class you want to proxy, or from the appropriate superclass / interface.
As soon as you do this, it'll have the relevant methods statically provided, so applyDynamic would never be considered.

I think your odds are bad. Scala will call applyDynamic only if there is no static match on the method call:
class Slow {
def doStuff = //slow stuff
}
var slow = new Slow with DynamicTimer
slow.doStuff
In the example above, scalac won't call applyDynamic because it statically resolved your call to doStuff. It will only fall through to applyDynamic if the method you are calling matches none of the names of methods on the type.

Related

Quick Documentation For Scala Apply Constructor Pattern in IntelliJ IDE

I am wondering if there is a way to get the quick documentation in IntelliJ to work for the class construction pattern many scala developers use below.
SomeClass(Param1,Parma2)
instead of
new SomeClass(param1,Param2)
The direct constructor call made with new obviously works but many scala devs use apply to construct objects. When that pattern is used the Intelij documentation look up fails to find any information on the class.
I don't know if there are documents in IntelliJ per se. However, the pattern is fairly easy to explain.
There's a pattern in Java code for having static factory methods (this is a specialization of the Gang of Four Factory Method Pattern), often along the lines of (translated to Scala-ish):
object Foo {
def barInstance(args...): Bar = ???
}
The main benefit of doing this is that the factory controls object instantiation, in particular:
the particular runtime class to instantiate, possibly based on the arguments to the factory. For example, the generic immutable collections in Scala have factory methods which may create optimized small collections if they're created with a sufficiently small amount of contents. An example of this is a sequence of length 1 can be implemented with basically no overhead with a single field referring to the object and a lookup that checks if the offset is 0 and either throws or returns its sole field.
whether an instance is created. One can cache arguments to the factory and memoize or "hashcons" the created objects, or precreate the most common instances and hand them out repeatedly.
A further benefit is that the factory is a function, while new is an operator, which allows the factory to be passed around:
class Foo(x: Int)
object Foo {
def instance(x: Int) = new Foo(x)
}
Seq(1, 2, 3).map(x => Foo(x)) // results in Seq(Foo(1), Foo(2), Foo(3))
In Scala, this is combined with the fact that the language allows any object which defines an apply method to be used syntactically as a function (even if it doesn't extend Function, which would allow the object to be passed around as if it's a function) and with the "companion object" to a class (which incorporates the things that in Java would be static in the class) to get something like:
class Foo(constructor_args...)
object Foo {
def apply(args...): Foo = ???
}
Which can be used like:
Foo(...)
For a case class, the Scala compiler automatically generates a companion object with certain behaviors, one of which is an apply with the same arguments as the constructor (other behaviors include contract-obeying hashCode and equals as well as an unapply method to allow for pattern matching).

Scala Argument Capture of External Class

So I want to check arguments that I send to an external class that I do not control. The external class is assumed tested, I simply want to test if I passed it the right parameters. I have tried some combination of ArgumentCaptor etc, but not much luck
import org.ABC.ExternalClass
case class Foo(i:Int, j: Int...) {
val EC = CreateExternalClass()
def CreateExternalClass(): ExternalClass = {
new ExternalClass (i, j, ....many parameters)
}
}
I think you are getting things wrong here: you can only use an ArgumentCaptor on calls to mocked objects. You can't use them to "intercept" arbitrary calls between all kinds of objects.
Meaning: you could only use an ArgumentCaptor if you would be using a mocked ExternalClass object. But then you would not need to capture, as you probably could do simply method call argument verification.
But of course, you can't use Mockito to mock that call to new in your production class. The options you have:
Turn to PowerMockito or JMockit; frameworks that allow to mock calls to new. Not recommended.
Rework your production code to not do that call to new. Probably not helpful here; as this class might already be a wrapper around that external class
Go for checking on the created object: check if you could use getter methods to simply query the newly created object to have the values that you expect to show up inside

Is there any workaround for Scala bug SI-7914 - returning an apply method from a Scala macro?

In our library we have a macro defined like so:
def extractNamed[A]: Any = macro NamedExtractSyntax.extractNamedImpl[A]
This macro uses its type signature to return an apply method whose arguments match the apply method of the case class on which it is typed.
The idea is that this allows the user of our library to make use of Scala's named parameters like so:
lazy val fruitExtractor = extractNamed[Fruit](
name = FruitTable.name,
juiciness = FruitTable.juiciness
)
However, this doesn't seem to work - it instead returns error: Any does not take parameters at compile-time.
It seems like this is caused by SI-7914 because it does work if the user explicitly calls apply, i.e.:
lazy val fruitExtractor = extractNamed[Fruit].apply(
name = FruitTable.name,
juiciness = FruitTable.juiciness
)
We can work around this by simply renaming the returned method to something sensible, but is there any other way to work around this without requiring an explicit method call?
How about returning an subclass of Dynamic from a macro? Then you could define applyDynamic and applyDynamicNamed to do what you want. For additional compile-time safety, you can have those xxxDynamic methods be macros as well. I just checked and this works exactly with the syntax that you want to have.

Scala - Can implicitNotFound annotation be applied at the method level?

I have a method that takes type parameters with an implicit view bounds on them. Can I use the #implicitNotFound annotation to give nicer compiler errors when the method is called with invalid data types?
The documentation for the method is useless and even the source code doesn't help, and all the examples of use online are at the trait or class level.
No, you cannot directly do that. As you’ve noticed, #implicitNotFound annotates traits or classes. You could, however, make a special implicit type just for that method and annotate it if you really wanted to have a custom message.

TS Interface doesn't force functions signature on implementers

interface test{
foo(boo:string);
}
class coo implements test{
foo(){
}
}
In playGround
this doesn't generate and error although the function signature is not as the interface
says, the expected behavior of interface is to force the signature..
why is this behavior?
Thanks
This is interesting. The TypeScript team are quite clever chaps and they decided to do this deliberately.
The idea is that if your function can operate correctly without being passed an argument, it can safely ignore the argument and satisfy the interface. This means you can substitute your implementation without having to update all of the calling code.
The interface ensures that the argument is passed in all cases where you are consuming the interface - so you get type checking on the callers and it actually doesn't matter that your concrete class doesn't need any parameters.
Interface Function Parameter Not Enforced
I am not satisfied how Interface doesn't enforce the method signature too. I believe the explanations by Fenton are wrong. The real reason is that Typescript is using "duck typing". No erros with less parameters, but you do get errors if you use more parameters.The long answer can be found here Why duck typing is allowed for classes in TypeScript
In the end, Interface can't fit the role of an abstract class that is extended by an other class. I wouldn't recommend to use Interface with classes but instead better use the word "implements" on an actual class, it does the same without the extra Interface class.
Typescript uses structural typing. The implemented function can have fewer parameters than the function declaration in the interface but not more.