"this" inside of object in coffee script class - coffeescript

Inside my class I have object (just to put all related functions for convenience) so then I call them "this" point to the current object.
For example:
class Test
constructor: ->
#vir = ""
helpers:
func1: ->
#vir = "a" (I can't do it because this point to object "func1")
func2: ->
Actually, I can pass my root object (or that global variable) as parameter but I want to know the coffee script way, maybe there is another way as "=>" for events?

CoffeeScript classes don't quite work that way. When you say things like:
class C
helpers:
f: -> console.log(#)
the helpers will just be an object attached to C's prototype. There won't be any special attachment to C so this:
c = new C
c.helpers.f()
is the same as:
c = new C
h = c.helpers
h.f()
and both will dump helpers itself in the console.
You can't use => to help anything here because, again, helpers is just an object with no special connection to C. So if you try this:
class C
helpers:
f: => console.log(#)
c = new C
c.helpers.f()
you'll get C itself in the console. This happens because f here is just a function inside an object that's attached to C's prototype, f isn't really a method at all.
There are a few ways around this.
Get rid of helpers completely and use =>:
class Test
constructor: -> #vir = ""
func1: => #vir = "a"
t = new Test
f = t.func1
f() # # is what you expect it to be
Bind all the functions inside helpers when you create a new instance:
class Test
constructor: ->
#vir = ""
helpers = { }
helpers[name] = f.bind(#) for name, f of #helpers
#helpers = helpers # Be careful not to mess up the prototype
helpers:
func1: -> #vir = "a"
t = new Test
f = t.helpers.func1
f()
Bind the functions when you give them to your event handling system:
class Test
constructor: -> #vir = ""
helpers:
func1: -> #vir = "a"
t = new Test
whatever.on('some-event', t.helpers.func1.bind(t))
Tell the event handling system what # should be. Some event systems let you specify what this to use when calling event handlers, I don't know what's managing your events so this may or may not be applicable.
class Test
constructor: -> #vir = ""
helpers:
func1: -> #vir = "a"
t = new Test
whatever.on('some-event', t.helpers.func1, t) # Assuming your event system understands a "context" argument
There are certainly other ways around this but I think the above are the most common approaches.

Related

Can't understand path dependent type

For a class C, you can use the familiar this inside the body to refer to the current instance, but this is actually a shorthand for C.this in Scala:
class C {
var x = "1"
def setX1(x:String) = this.x = x
def setX2(x:String) = C.this.x = x
}
I just can't understand C.this, C is a class, I can't understand why we use dot between C and this as shown in C.this?
I can't understand why we use dot between C and this as shown in
C.this
Using the class name before this is called a Qualified this in Java (see Using "this" with class name) and is similar in Scala. You use it when you want to reference an outer class from an inner class. Let's assume for example that you had a method declaration in your C class where you wanted to call this and mean "the this reference of C:
class C {
val func = new Function0[Unit] {
override def apply(): Unit = println(this.getClass)
}
}
new C().func()
Yields:
class A$A150$A$A150$C$$anon$1
You see the anon$1 at the end of the getClass name? It's because inside the function instance this this is actually of the function class. But, we actually wanted to reference the this type of C instead. For that, you do:
class C {
val func = new Function0[Unit] {
override def apply(): Unit = println(C.this.getClass)
}
}
new C().func()
Yields:
class A$A152$A$A152$C
Notice the C at the end instead of anon$1.

What are the Kotlin class initialisation semantics?

I haven't been able to find anything in the language definition that explains the initialisation of a class in Kotlin.
import java.util.Properties
fun main(args: Array<String>) {
val out = MyClass()
out.fn()
}
class MyClass {
private val a = Properties() // 1
init {
fn()
}
public fun fn() {
println("Fn called. a = $a")
}
// private val a = Properties() // 2
}
The results of running this program change depending whether the property is initialised at (1) or at (2).
I'm surprised that the declaration order is relevant in the language and would like to understand the decisions behind this. My expectation would be that properties are initialised before the constructor body is invoked.
My expectation would be that properties are initialised before the constructor body is invoked.
Well, init block is not a constructor. It is a different construct which allows you to perform the initialization of the object and they [init blocks] are performed in the declaration order with the property initializers.
Constructors are a different beast ant they are performed after all the properties were initialized and all init blocks were performed. Look at the following example:
class A(val value: Int) {
constructor(): this(0) {
println("Constructor")
}
init {
println("Init block")
}
}
fun main(args: Array<String>) {
val a = A()
}
Output is:
Init block
Constructor
You can place the init block wherever you want: before the constructor or after it; it will always be performed before the A's constructor (secondary constructor, in this example).
Simply put: when an instance of a class is created, (almost) firstly runs the constructor of the parent class (if present), then the primary constructor.
The primary constructor executes code declared in the class body from the top to the bottom. Also the names became available by the same rule:
class Foo(a: String = "might be first"
val b: String = "second" + a) : Boo(a + b + "third"){
var c = a + "fourth" + b
init {print("fifth: $c")}
val d = "sixth"
init {print("seventh: the end of the primary constructor"}
}
If you invoke a secondary constructor, then it works after the primary one as it is composed in the chain (similar to invoking the parent constructors).

How to create a Scala class with private field with public getter, and primary constructor taking a parameter of the same name

Search results so far have led me to believe this is impossible without either a non-primary constructor
class Foo { // NOT OK: 2 extra lines--doesn't leverage Scala's conciseness
private var _x = 0
def this(x: Int) { this(); _x = x }
def x = _x
}
val f = new Foo(x = 123) // OK: named parameter is 'x'
or sacrificing the name of the parameter in the primary constructor (making calls using named parameters ugly)
class Foo(private var _x: Int) { // OK: concise
def x = _x
}
val f = new Foo(_x = 123) // NOT OK: named parameter should be 'x' not '_x'
ideally, one could do something like this:
class Foo(private var x: Int) { // OK: concise
// make just the getter public
public x
}
val f = new Foo(x = 123) // OK: named parameter is 'x'
I know named parameters are a new thing in the Java world, so it's probably not that important to most, but coming from a language where named parameters are more popular (Python), this issue immediately pops up.
So my question is: is this possible? (probably not), and if not, why is such an (in my opinion) important use case left uncovered by the language design? By that, I mean that the code either has to sacrifice clean naming or concise definitions, which is a hallmark of Scala.
P.S. Consider the case where a public field needs suddenly to be made private, while keeping the getter public, in which case the developer has to change 1 line and add 3 lines to achieve the effect while keeping the interface identical:
class Foo(var x: Int) {} // no boilerplate
->
class Foo { // lots of boilerplate
private var _x: Int = 0
def this(x: Int) { this(); _x = x }
def x = _x
}
Whether this is indeed a design flaw is rather debatable. One would consider that complicating the syntax to allow this particular use case is not worthwhile.
Also, Scala is after all a predominantly functional language, so the presence of vars in your program should not be that frequent, again raising the question if this particular use case needs to be handled in a special way.
However, it seems that a simple solution to your problem would be to use an apply method in the companion object:
class Foo private(private var _x: Int) {
def x = _x
}
object Foo {
def apply(x: Int): Foo = new Foo(x)
}
Usage:
val f = Foo(x = 3)
println(f.x)
LATER EDIT:
Here is a solution similar to what you originally requested, but that changes the naming a bit:
class Foo(initialX: Int) {
private var _x = initialX
def x = _x
}
Usage:
val f = new Foo(initialX = 3)
The concept you are trying to express, which is an object whose state is mutable from within the object and yet immutable from the perspective of other objects ... that would probably be expressed as an Akka actor within the context of an actor system. Outside the context of an actor system, it would seem to be a Java conception of what it means to be an object, transplanted to Scala.
import akka.actor.Actor
class Foo(var x: Int) extends Actor {
import Foo._
def receive = {
case WhatIsX => sender ! x
}
}
object Foo {
object WhatIsX
}
Not sure about earlier versions, but In Scala 3 it can easily be implemented like follows:
// class with no argument constructor
class Foo {
// prive field
private var _x: Int = 0
// public getter
def x: Int = _x
// public setter
def x_=(newValue: Int): Unit =
_x = newValue
//auxiliary constructor
def this(value: Int) =
this()
_x = value
}
Note
Any definition within the primary constructor makes the definition public, unless you prepend it with private modifier
Append _= after a method name with Unit return type to make it a setter
Prepending a constructor parameter neither with val nor with var, makes it private
Then it follows:
val noArgFoo = Foo() // no argument case
println(noArgFoo.x) // the public getter prints 0
val withArgFoo = Foo(5) // with argument case
println(withArgFoo.x) // the public getter prints 5
noArgFoo.x = 100 // use the public setter to update x value
println(noArgFoo.x) // the public getter prints 100
withArgFoo.x = 1000 // use the public setter to update x value
println(withArgFoo.x) // the public getter prints 1000
This solution is exactly what you asked; in a principled way and without any ad hoc workaround e.g. using companion objects and the apply method.

scala copy objects

Is there a way to make a copy of an object (or even better a list of objects)?
I'm talking about custom objects of classes that may be extended by other classes.
example:
class Foo() {
var test = "test"
}
class Bar() extends Foo {
var dummy = new CustomClass()
}
var b = new Bar()
var bCopy = b.copy() // or something?
In Java, they tried to solve this problem a clone method, that works by invoking clone in all super-classes, but this is generally considered broken and best avoided, for reasons you can look up (for example here).
So in Scala, as genereally in Java, you will have to make your own copy method for an arbitrary class, which will allow you to specify things like deep vs shallow copying of fields.
If you make you class a case class, you get a copy method for free. It's actually better than that, because you can update any of the fields at the same time:
case class A(n: Int)
val a = A(1) // a: A = A(1)
val b = a.copy(a.n) // b: A = A(1)
val c = a.copy(2) // c: A = A(2)
However inheriting from case classes is deprecated.

scala auto convert functions / methods?

I have got a class with many methods.
class C{
def f1(x:String,....):...=..
def f2(..)...
.
.
.
}
I want now that every method defined in my class is decorated with a trait of my choice automatically.
Something like to create a tricky implicit ore something what decorates every method and perhaps returns an instance of the class with decorated methods. Perhaps wrapped or modified or something. I can not describe more of the way because i dont know the way.
Do you know a way to do that?
Methods are not functions, although they will automatically be lifted when you pass them to a method that requires a function. See also http://jim-mcbeath.blogspot.com/2009/05/scala-functions-vs-methods.html
If you really have functions:
class C {
val f1 = (x: String, ...) =>
val f2 = (...) =>
...
}
and you want them to mix in a trait, like:
class C {
val f1 = new FunctionN[String, ...] with Gaga {
def apply(s: String, ...) = ...
}
val f2 = new FunctionN[...] with Gaga { ... }
...
}
the only way I can think of is submit your class to something like Scala-Refactoring: http://scala-refactoring.org/