What's a clean way to check for an objects type? - gwt

I want to make a distinction in my code based on the type of an object.
What is a clean (and performant) way to accomplish that?
My object will either be an instance of class A,B or C. All of them extend a class S.
if (obj instanceof A) {...}
Would be what I do in plain java. Is this also good in GWT (or JavaScript at the end)?

Basically the answer is yes if you have declarations like this,
S objA = new A();
S objB = new B();
S objC = new C();
if(objA instacneofc A) //true
if(objB instacneofc A) //false
if(objC instacneofc C) //true

Related

How to extend a functionN class in Scala

I am new to Scala.
I have a Class A that extends a Class C. I also have a Class B that also extends a Class C
I want function objects of type A->B to extend C as well (and also other derived types, such as A->(A->B)). But I read in "Programming in scala" following:
A function literal is compiled into a class that when instantiated at runtime
is a function value.
Is there some way of automatically letting A->B extend C, other then manually having to create a new class that represents the function?
Functions in Scala are modelled via FunctionN trait. For example, simple one-input-one-output functions are all instances of the following trait:
trait Function1[-T1, +R] extends AnyRef
So what you're asking is "how can I make instances of Function also become subclasses of C". This is not doable via standard subtyping / inheritance, because obviously we can't modify the Function1 trait to make it extend your custom class C. Sure, we could make up a new class to represent the function as you suggested, but that will only take us so far and it's not so easy to implement, not to mention that any function you want to use as C will have to be converted to your pseudo-function trait first, which will make things horrible.
What we can do, however, is create a typeclass which then contains an implementation for A -> B, among others.
Let's take the following code as example:
trait A
trait B
trait C[T]
object C {
implicit val fa = new C[A] {}
implicit val fb = new C[B] {}
implicit val fab = new C[Function1[A, B]] {}
}
object Test extends scala.App {
val f: A => B = (a: A) => new B {}
def someMethod[Something: C](s: Something) = {
// uses "s", for example:
println(s)
}
someMethod(f) // Test$$$Lambda$6/1744347043#dfd3711
}
You haven't specified your motivation for making A -> B extend C, but obviously you want to be able to put A, B and A -> B under the "same umbrella" because you have, say, some method (called someMethod) which takes a C so with inheritance you can pass it values of type A, B or A -> B.
With a typeclass you achieve the same thing, with some extra advantages, such as e.g. adding D to the family one day without changing existing code (you would just need to implement an implicit value of type C[D] somewhere in scope).
So instead of having someMethod take instances of C, it simply takes something (let's call it s) of some type (let's call it Something), with the constraint that C[Something] must exist. If you pass something for which an instance of C doesn't exist, you will get an error:
trait NotC
someMethod(new NotC {})
// Error: could not find implicit value for evidence parameter of type C[NotC]
You achieve the same thing - you have a family of C whose members are A, B and A => B, but you go around subtyping problems.

Using a Lens on a non-case class extending something with a constructor in Scala

I am probably thinking about this the wrong way, but I am having trouble in Scala to use lenses on classes extending something with a constructor.
class A(c: Config) extends B(c) {
val x: String = doSomeProcessing(c, y) // y comes from B
}
I am trying to create a Lens to mutate this class, but am having trouble doing so. Here is what I would like to be able to do:
val l = Lens(
get = (_: A).x,
set = (c: A, xx: String) => c.copy(x = xx) // doesn't work because not a case class
)
I think it all boils down to finding a good way to mutate this class.
What are my options to achieve something like that? I was thinking about this in 2 ways:
Move the initialization logic into a companion A object into a def apply(c: Config), and change the A class to be a case class that gets created from the companion object. Unfortunately I can't extend from B(c) in my object because I only have access to c in its apply method.
Make x a var. Then in the Lens.set just A.clone then set the value of x then return the cloned instance. This would probably work but seems pretty ugly, not to mention changing this to a var might raise a few eyebrows.
Use some reflection magic to do the copy. Not really a fan of this approach if I can avoid it.
What do you think? Am I thinking about this really the wrong way, or is there an easy solution to this problem?
This depends on what you expect your Lens to do. A Lens laws specify that the setter should replace the value that the getter would get, while keeping everything else unchanged. It is unclear what is meant by everything else here.
Do you wish to have the constructor for B called when setting? Do you which the doSomeProcessing method called?
If all your methods are purely functional, then you may consider that the class A has two "fields", c: Config and x: String, so you might as well replace it with a case class with those fields. However, this will cause a problem while trying to implement the constructor with only c as parameter.
What I would consider is doing the following:
class A(val c: Config) extends B(c) {
val x = doSomeProcessing(c, y)
def copy(newX: String) = new A(c) { override val x = newX }
}
The Lens you wrote is now perfectly valid (except for the named parameter in the copy method).
Be careful if you have other properties in A which depend on x, this might create an instance with unexpected values for these.
If you do not wish c to be a property of class A, then you won't be able to clone it, or to rebuild an instance without giving a Config to your builder, which Lenses builder cannot have, so it seems your goal would be unachievable.

What does 'this: =>' construct mean?

I've seen a couple of time code like this in Scala libraries. What does it mean?
trait SecuredSettings {
this: GlobalSettings =>
def someMethod = {}
...
}
This trick is called "self type annotation".
This actually do two separate things at once:
Introduces a local alias for this reference (may be useful when you introduce nested class, because then you have several this objects in scope).
Enforces that given trait is mixable only into subtypes of some type (this way you assume you have some methods in scope).
Google for "scala self type annotation" for many discussion about this subject.
The scala-lang.org contains a pretty descent explanation of this feature:
http://docs.scala-lang.org/tutorials/tour/explicitly-typed-self-references.html
There are numerous patterns which use this trick in non-obvious way. For a starter, look here:
http://marcus-christie.blogspot.com/2014/03/scala-understanding-self-type.html
trait A {
def foo
}
class B { self: A =>
def bar = foo //compiles
}
val b = new B //fails
val b = new B with A //compiles
It means that any B instances must inherit (mix-in) A. B is not A, but its instances are promised to be so, therefore you can code B as if it were already A.

Cannot compile file in Scala

From an example in book "Begining in Scala", the script is:
import scala.collection.mutable.Map
object ChecksumAccumulator {
private val cache=Map[String,Int]()
def calculate(s: String):Int =
if(cache.contains(s))
cache(s)
else{
val acc = new ChecksumAccumulator
for(c <- s)
acc.add(c.toByte)
val cs=acc.checksum
cache+= (s -> cs)
cs
}
}
but, when I tried to compile this file
$scalac ChecksumAccumulator.scala, then generate an error, "not found: type ChecksumAccumulator val acc = new ChecksumAccumulator", any suggest?
Thanks,
'object' keyword defines a singleton object, not a class. So you can't new an object, the 'new' keyword requires a class.
check this Difference between object and class in Scala
You probably left some code out that looks like
class ChecksumAccumulator {
//...
}
The other answers are correct in saying what the problem is, but not really helping you understand why the example from the book is apparently not correct.
However, if you look at the Artima site, you will find the example is in a file here
Your code is an incomplete fragment. The file also includes these lines
// In file ChecksumAccumulator.scala
class ChecksumAccumulator {
private var sum = 0
def add(b: Byte) { sum += b }
def checksum(): Int = ~(sum & 0xFF) + 1
}
... without which you will get the error you had.
your issue is here
val acc = new ChecksumAccumulator
you cannot use new keyword with the object.
objects cannot be re-instantiated. You always have single instance of an object in scala. This is similar to static members in java.
Your code, probably meant as a companion object. That's kinda factories in imperative languages.
Basicaly, you have object and class pair. Object (singleton in imperative langs) can't be instantiated multiple times, as people here already noted, and usually used to define some static logic. In fact, there is only one instantiation -- when you call him for the first time. But object can have compaion -- regular class, and, as I think you've missed definition of that regular class, so object can't see anyone else, but itself.
The solution is to define that class, or to omit new (but i think that would be logicaly wrong).

Why isn't opAssign overloadable for classes?

This D specification table says that assignment overloading is only possible for structs, not classes. This surprises me. Isn't the syntactic sugar of A = B harmless? What was the design rationale for restricting it to structs?
In D, classes are used by reference. So, when you do A = B, you do not copy the object itself, but just a reference to that object.
None of objects are modified during the process. So it makes no sense to define opAssign for thoses.
D classes have reference semantics. If you want a way to get a copy of the object (it think) the standard or conventional thing to do is provide a .dup property.
I would file a bug, and did. The general rule is to follow The D Programming Language by Andrei Alexandrescu, the DMD implementation, and then the website. As I don't have a copy of The D Programming Language handy, I'm going with the DMD implementation on this:
class A {
int a;
string b;
float c;
void opAssign(B b) {
a = b.a;
}
}
class B {
int a;
}
void main()
{
auto a = new A();
a.a = 5;
auto b = new B();
b.a = 10;
a = b;
assert(a.a == 10);
}