Extend a CoffeeScript class loaded with RequireJS inside a TypeScript code - coffeescript

Currently I have a large codebase developed with CoffeeScript and want to extend it with some TypeScript.
Let's say I have the following code in the CoffeeClass.coffee file:
define 'CoffeeClass', ->
class CoffeeClass
foo: () -> 1
It is meant to be loaded through require in the following manner (let's call this file CoffeeUser.coffee):
require ['CoffeeClass'], (CoffeeClass) ->
class MyClass extends CoffeeClass
foo: () -> super() + 1
console.log (new MyClass().foo()) # => 2
Now it can be loaded in browser with the standard RequireJS markup:
<script data-main="CoffeeUser.js" src="require.js"></script>
I want to extend the CoffeeClass from the TypeScript code. That's what I've tried:
First write a CoffeeClass.d.ts definiton file (I know it is wrong but it's showing what I'm trying to achieve):
export class CoffeeClass {
foo(): number;
}
And then try to use it from TypeScriptUser.ts:
import CoffeeClass = require('CoffeeClass');
class TypeScriptUser extends CoffeeClass {
foo(): number {
return super.foo() + 1;
}
}
But it won't compile partly because I cannot find the right syntax for the d.ts file and partly because I cannot properly tell the compiler how to extend the CoffeeClass (as far as I can tell the compiler cannot understand that CoffeeClass is really a class and not just a module).
So can I tell the TypeScript compiler that the module is a class here? If no, how would you recommend me to change the CoffeeClass design to extend it from TypeScript code and don't lose all the type safety?

Finally I've found the solution. That's the special export = syntax. Here it is. CoffeeClass.d.ts:
declare class CoffeeClass {
foo(): number;
}
export = CoffeeClass;
And TypeUser.ts:
/// <reference path="CoffeeClass.d.ts" />
import CoffeeClass = require('CoffeeClass')
class MyClass extends CoffeeClass {
foo() {
return super.foo() + 1;
}
}
console.log(new MyClass().foo()); // => 2
Note that the compiler will infer the proper require call when compiling the code.

Related

scala - mock function and replace implementation in tests

I'm using scalatest and when I test my code, I want to replace an implementation of a function to return something else when running tests.
In JavaScript its really simple and I thought I could do the same in scala.
So what I want is something like this:
object Module {
private def bar(): Int = {
5
}
def foo(): Unit = {
println(bar())
}
}
And the test will be something like that (dont mind the syntax, you get the idea)
class Test extends FunSpec {
mock(Module.bar, () => 1)
describe("Test") {
it("Test") {
Module.foo() // will print 1
}
}
}
I have searched the internet and came across scala mock libraries but none of them seemed to be able to replace the implementation of a method.
In every library you have to defined your mock in the test and pass it on to the code, but I don't want to do that.
Is there anyway to achieve this?
Thank you.
You can't mock Object in Scala, because it's like a static class in java (which you can't mock either). (and you can't mock scala objects not in mockito nor scalamock (maybe in their next version)).
But, if you change your object Module to class Module, you can mock this function easily (using mockito):
val mockModule = mock[Module]
when(mockModule.bar()).thenReturn(1)
You can do a fake class that has that function and put the value you want, if you dont want to use mocks, like this:
trait SMT{
def bar: Int
}
class RealImpl extends SMT{
def bar: Int = 5
}
class FakeImpl extends SMT{
def bar: Int = 1
}

Why Fantom compiler complains about a class that has a Func field?

I wrote a Fantom script that defines a bunch of classes. As I could run the script successfully, I decided to convert this into a proper Fantom project, but one of the classes cannot be compiled and the error message is:
Expected expression, not '|'
The class has this form:
class MyClass
{
const Func myFunc := |Foo foo, Bar bar| {
// do stuff
}
MyType myVar := MyType()
Void main() {
// do more stuff
}
}
I don't understand why the compiler complains when this class is part of a Fantom project, but doesn't if is part of a Fantom script instead. Can anyone shed some light, please?
Thank you
It's a just a bad error message on Fantom's behalf. It is actually complaining that the classes Foo and Bar don't exist. Add the following to your project and all should compile okay.
class Foo {}
class Bar {}
class MyType {}

How can I find where does a method definition rather then declaration in idea IDE?

In scala, class could combine with many trait and it's difficult to find a method definition.Does the function exist in idea?
Example:
trait A {
def name: String
}
class AChildren extends A {
def name = "AChildren"
}
class B(val a: A) {
}
object main extends App {
val bInstance = new B(new AChildren())
bInstance.a.name
}
When you use ctrl/cmd + B on name of bInstance.a.name, idea will help you trace to A.name.Obviously, useful information is AChildren.name, it implements executable code. Could it can point to AChildren.name?
In IntelliJ IDEA, move your cursor to the function call and press ctrl+b. This should open the function definition (unless you changed the hotkey ofc.)

Scala interop with Java questionmark generics

EDIT I have made the example self-contained.
Suppose in java I have
src/main/java/FooFactory.java
interface FooFactory {
Foo<?> create();
<T> void enhance(Foo<T> foo, FooEnhancer<? super T> enhancer);
}
and src/main/java/Foo.java
interface Foo<T> {}
and src/main/java/FooEnhancer.java
interface FooEnhancer<T> {}
(and you can't change these interfaces because they belong to someone else.)
Then in scala you have
object DummyFooEnhancer extends FooEnhancer[Any]
trait FooHdlr {
def fooFactory: FooFactory
val foo = fooFactory.create
fooFactory.enhance(foo, DummyFooEnhancer)
}
This doesn't compile because FooEnhancer and Foo are invariant but foo is a Foo<?> whereas DummyFooEnhancer is a Foo[Any]. Changing Any to AnyRef doesn't work for the same reason.
Then I reasoned that, well, ? is a specific type that is certainly not known at compile time and that may not necessarily be AnyRef/Object, so what if I do this?
case class DummyFooEnhancer[T] extends FooEnhancer[T]
trait FooHdlr {
def fooFactory: FooFactory
val foo = fooFactory.create
fooFactory.enhance(foo, new DummyFooEnhancer)
}
But this causes scalac to stackoverflow! It's looping with
at scala.reflect.internal.Types$TypeVar.isGround(Types.scala:3082)
calling itself.
Interestingly if I replace ? super T with T it works fine, but in real life I can't do this because it's in code I don't control

How to implement intermediate types for implicit methods?

Assume I want to offer method foo on existing type A outside of my control. As far as I know, the canonical way to do this in Scala is implementing an implicit conversion from A to some type that implements foo. Now I basically see two options.
Define a separate, maybe even hidden class for the purpose:
protected class Fooable(a : A) {
def foo(...) = { ... }
}
implicit def a2fooable(a : A) = new Fooable(a)
Define an anonymous class inline:
implicit def a2fooable(a : A) = new { def foo(...) = { ... } }
Variant 2) is certainly less boilerplate, especially when lots of type parameters happen. On the other hand, I think it should create more overhead since (conceptually) one class per conversion is created, as opposed to one class globally in 1).
Is there a general guideline? Is there no difference, because compiler/VM get rid of the overhead of 2)?
Using a separate class is better for performance, as the alternative uses reflection.
Consider that
new { def foo(...) = { ... } }
is really
new AnyRef { def foo(...) = { ... } }
Now, AnyRef doesn't have a method foo. In Scala, this type is actually AnyRef { def foo(...): ... }, which, if you remove AnyRef, you should recognize as a structural type.
At compile time, this time can be passed back and forth, and everywhere it will be known that the method foo is callable. However, there's no structural type in the JVM, and to add an interface would require a proxy object, which would cause some problems such as breaking referential equality (ie, an object would not be equal with a structural type version of itself).
The way found around that was to use cached reflection calls for structural types.
So, if you want to use the Pimp My Library pattern for any performance-sensitive application, declare a class.
I believe 1 and 2 get compiled to the same bytecode (except for the class name that gets generated in case 2).
If Fooable exists only for you to be able to convert implicitly A to Fooable (and you're never going to directly create and use a Fooable), then I would go with option 2.
However, if you control A (meaning A is not a java library class that you can't subclass) I would consider using a trait instead of implicit conversions to add behaviour to A.
UPDATE:
I have to reconsider my answer. I would use variant 1 of your code, because variant 2 turns out to be using reflection (scala 2.8.1 on Linux).
I compiled these two versions of the same code, decompiled them to java with jd-gui and here are the results:
source code with named class
class NamedClass { def Foo : String = "foo" }
object test {
implicit def StrToFooable(a: String) = new NamedClass
def main(args: Array[String]) { println("bar".Foo) }
}
source code with anonymous class
object test {
implicit def StrToFooable(a: String) = new { def Foo : String = "foo" }
def main(args: Array[String]) { println("bar".Foo) }
}
compiled and decompiled to java with java-gui. The "named" version generates a NamedClass.class that gets decompiled to this java:
public class NamedClass
implements ScalaObject
{
public String Foo()
{
return "foo";
}
}
the anonymous generates a test$$anon$1 class that gets decompiled to the following java
public final class test$$anon$1
{
public String Foo()
{
return "foo";
}
}
so almost identical, except for the anonymous being "final" (they apparently want to make extra sure you won't get out of your way to try and subclass an anonymous class...)
however at the call site I get this java for the "named" version
public void main(String[] args)
{
Predef..MODULE$.println(StrToFooable("bar").Foo());
}
and this for the anonymous
public void main(String[] args) {
Object qual1 = StrToFooable("bar"); Object exceptionResult1 = null;
try {
exceptionResult1 = reflMethod$Method1(qual1.getClass()).invoke(qual1, new Object[0]);
Predef..MODULE$.println((String)exceptionResult1);
return;
} catch (InvocationTargetException localInvocationTargetException) {
throw localInvocationTargetException.getCause();
}
}
I googled a little and found that others have reported the same thing but I haven't found any more insight as to why this is the case.