I am a newcomer to Scala. In 2.7.7, the following code
abstract class C
case class CC() extends C
trait T
val c1 = CC()
val c2 = new CC() with T
println(c1.hashCode == c2.hashCode,c1 equals c2)
prints
(false,true)
whereas I would have expected
(false,false)
What am I missing? Thanks in advance.
Case class equality (particularly in Scala 2.8) equality and hash codes are based upon tuple and/or product equality, and do not currently take the class into account. There was a recent discussion on this matter on the scala-debate mailing list here: http://old.nabble.com/Possible-Collision-Issue-with-Product.hashCode-td27026790.html
For what it's worth, here's what it currently looks like in 2.8:
Welcome to Scala version 2.8.0.Beta1-RC6 (Java HotSpot(TM) Client VM, Java 1.6.0_16).
Type in expressions to have them evaluated.
Type :help for more information.
scala> abstract class C
defined class C
scala> case class CC() extends C
defined class CC
scala> trait T
defined trait T
scala> val c1 = CC()
c1: CC = CC()
scala> val c2 = new CC() with T
c2: CC with T = CC()
scala> println(c1.hashCode == c2.hashCode,c1 equals c2)
(true,true)
This behaviour is expected for equals since the Scala compiler overrides the equals method for case classes.
I am however unsure why the hashCode is different in Scala 2.7.7. Your example results in (true, true) using Scala 2.8.
Related
Scala's TypeTags are relatively easy to compare, and capture - but does Scala offer any composition function that act on 2 tags? For example, I'm working with tags in a very generalized way (meaning, type T is gone). Can I request Scala to provide me a TypeTag of the least common parent? This would seem logical since the compiler and various editor IDEs do this with ease and show the common parent. Example:
Class A
Class B extends A
class C extends A
val tagB:TypeTag[_] = implicitly[TypeTag[B]]
val tagC:TypeTag[_] = implicitly[TypeTag[C]]
val res:TypeTag[_] = lcmFunction(tagB,tagC) //not a real function name .. example only
res // yields a TypeTag such that res.tpe =:= TypeTag[A].tpe
There is a lub method on Universe, which will compute the least upper-bound of a list of types.
class A
class B extends A
class C extends A
class D extends C
class E extends C
class F extends E
import scala.reflect.runtime.universe._
val a = typeTag[A]
val b = typeTag[B]
val c = typeTag[C]
val d = typeTag[D]
val e = typeTag[E]
val f = typeTag[F]
scala> lub(List(b.tpe, c.tpe))
res17: reflect.runtime.universe.Type = A
scala> lub(List(b.tpe, c.tpe)) =:= a.tpe
res18: Boolean = true
scala> lub(List(e.tpe, f.tpe))
res19: reflect.runtime.universe.Type = E
scala> lub(List(c.tpe, d.tpe, f.tpe))
res21: reflect.runtime.universe.Type = C
Creating a TypeTag out of the resulting Type is a little more tricky, it seems, but possible as seen in this answer.
I need to get all the interfaces at runtime from a given Class (all loaded in a ClassLoader).
For instance, if a class has been declared this way :
trait B
trait C
trait D
class A extends B with C with D
I want to get this information at runtime : A depends on B and C and D.
The java getInterfaces() (or the interfaces() from the clapper library) methods gives only the first dependency, namely: A depends on B.
Is there a way to achieve that ?
I guess by reflection but I don't know how ?
The solution I found with reflection :
import scala.reflect.runtime.{universe => ru}
val mirror = ru.rootMirror
val t = m.staticClass(classString).typeSignature
t.baseClasses
This question gives the answer:
import scala.reflect.runtime.universe._
trait B
trait C
class A extends B with C
val tpe = typeOf[A]
tpe.baseClasses foreach {s => println(s.fullName)}
// A, C, B, java.lang.Object, scala.Any
It works in the REPL, but when I put the code into a Scala script file and executed it, it didn't any longer:
typeOf[A]
// Compiler error: No TypeTag available for this.A
Using weakTypeTag instead didn't help either
weakTypeTag[A]
// Runtime error: scala.reflect.internal.FatalError:
// ThisType(free type $anon) for sym which is not a class
I got the same behaviour with Scala 2.10.0, 2.10.1 and 2.11.0-M2.
Given a reference to a case class companion object t and a sequence of parameter seq how can I invoke a new instance of the case class?
I can create a class when I type the number of the parameter by myself.
scala> case class B(n:String,a:Int,b:Int)
defined class B
scala> val t:AnyRef = B
t: AnyRef = B
scala> val m = t.getClass.getMethods.filter{m => m.getName == "apply"}.
filterNot {_.getReturnType.getName == "java.lang.Object"}(0)
m: java.lang.reflect.Method = public B B$.apply(java.lang.String,int,int)
scala> m.invoke(t,"name",1:java.lang.Integer,2:java.lang.Integer)
res99: Object = B(name,1,2)
The problem I couldn't solve is to call invoke with a sequence of arguments like Seq("name",1:java.lang.Integer,2:java.lang.Integer). Any help how to do that is greatly appreciated.
I use scala 2.10.0.
Just found it out by myself (respectively have seen it over here https://stackoverflow.com/a/2060503/55070). It's
method.invoke(t,seq: _*)
Sometimes it really helps to just write it down ;-)
As far as I've learned, traits in Scala are similar to interfaces in Java except methods are allowed to have an implementation. Also, in contrast to Scala classes, you can't pass them arguments for construction.
So far, so good. But why am I allowed to instantiate them? Really, I don't see a good reason to allow this.
You don't really instantiate them. As you drew a parallel with Java, let's go further into it. You are able in Java to build a Anonymous class out of an abstract class or of an Interface. It is almost the same in Scala:
scala> trait A
defined trait A
scala> new A {}
res0: A = $anon$1#5736ab79
Note that the curly braces are mandatory when you create an object from a trait. For example, yon cannot do:
scala> new A
<console>:9: error: trait A is abstract; cannot be instantiated
new A
^
While it would works perfectly for a class:
scala> class B
defined class B
scala> new B
res2: B = B#213526b0
Of course if some elements in your trait are not implemented, you need to implement them when you create the object:
scala> trait C {def foo: Int}
defined trait C
scala> new C {}
<console>:9: error: object creation impossible, since method foo in trait C of type => Int is not defined
new C {}
^
scala> new C {def foo = 42}
res4: C = $anon$1#744957c7
This may seem like a silly question, so bear with me...
Consider this REPL session:
scala> trait T
defined trait T
scala> val t = new T
<console>:8: error: trait T is abstract; cannot be instantiated
val t = new T
^
scala> val t = new T {}
t: java.lang.Object with T = $anon$1#78db81f3
scala> class C
defined class C
scala> val c = new C
c: C = C#170a6001
We can use a trait just like a class, except that we have to add {} after the new T. In fact, we're essentially mixing T into java.lang.Object, which actually makes a lot of sense to me.
If we have members, again only the {} must be added:
scala> trait T2 { val s = "test" }
defined trait T2
scala> val t2 = new T2
<console>:8: error: trait T2 is abstract; cannot be instantiated
val t2 = new T2
^
scala> val t2 = new T2 {}
t2: java.lang.Object with T2 = $anon$1#6a688d6f
scala> t2.s
res0: java.lang.String = test
scala> class C2 { val s = "test" }
defined class C2
scala> val c2 = new C2
c2: C2 = C2#73ea7821
scala> c2.s
res1: java.lang.String = test
If we have abstract members then the trait declaration is actually shorter by a few characters and, more importantly, more consistent in my eyes (no need to remember to put abstract in front of your declarations):
scala> trait T3 { val s: String }
defined trait T3
scala> val t3 = new T3 { val s = "test" }
t3: java.lang.Object with T3 = $anon$1#1f2f0ce9
scala> abstract class C3 { val s: String }
defined class C3
scala> val c3 = new C3 { val s = "test" }
c3: C3 = $anon$1#207a8313
If you forget that you must define some of the members, both ways give you compile errors:
scala> val badt3 = new T3 {}
<console>:7: error: object creation impossible, since value s in trait T3 of type String is not defined
val badt3 = new T3 {}
scala> class BadC3 { val s: String }
<console>:8: error: class BadC3 needs to be abstract, since value s is not defined
class BadC3 { val s: String }
And if we try to do more complex things then the power of traits naturally becomes further apparent:
scala> val t4 = new T with T2
t4: java.lang.Object with T with T2 = $anon$1#479e0994
scala> val c4 = new C with C2
<console>:9: error: class C2 needs to be a trait to be mixed in
val c4 = new C with C2
So again I ask, why does Scala bother with classes at all when traits are apparently both simpler and more powerful?
I assume the reason is conceptual and actual compatibility with Java, but I wonder whether code compatability could have been maintained behind the scenes. As I understand it, Scala traits just become Java classes behind the scenes, so why couldn't the reverse happen and Scala consider Java classes to essentially be traits?
Related to all this, why not allow dropping the curly brackets when unnecessary? For example:
val t = new T
At that point, as a user, traits would be indistinguishable from current Scala classes, but of course better.
There are several differences between traits and classes:
a trait can not take constructor parameters. This limitation might be lifted at some point, but it's a hard problem. A trait may be inherited multiple times in a hierarchy, and each instantiation may give different values for the constructor parameters
a trait is compiled to a Java interface and an implementation class (carrying the concrete methods). This means it's a bit slower, because all calls go through interfaces, and if they're concrete, they are forwarded to their implementation
a trait with concrete members can't be nicely inherited in Java (it could, but it would look like an interface, therefore concrete members would still need to be implemented in Java).
I don't think the distinction between classes and traits will go away, mostly because of the last two items. But they may become easier to use if the first point is solved. Regarding instantiation without the {}, that's a convenience that could be added, but I personally wouldn't like it: each instantiation creates a new class (an anonymous one), and there should be an indication to the programmer that that's the case.