ArrayBuilder has no method definitions:
abstract class ArrayBuilder[T] extends ReusableBuilder[T, Array[T]] with Serializable
Yet, implementations of it will commonly share methods with same interface, up to the generic type argument T (taking mkArray as an example):
final class ofFloat extends ArrayBuilder[Float] {
//...
private def mkArray(size: Int): Array[Float] = {
val newelems = new Array[Float](size)
if (this.size > 0) Array.copy(elems, 0, newelems, 0, this.size)
newelems
}
Methods creating new arrays couldn't be abstracted "up to the generic type argument T" before ClassTags were introduced; afterwards they could, but it would lose performance (probably very slightly in most circumstances, but this code is called quite often...).
Type erasure interacts weirdly with arrays. Any Array[T] you have in ArrayBuilder[T] will end up being Array[AnyRef]. So if you just have abstract methods there, classes like ofFloat will end up with a lot of hidden casts which JIT may or may not optimize.
Related
I am trying to understand the Mixins in the context of scala. In particular I wanted to know difference between concepts of inheritance and Mixins.
The definition of Mixin in wiki says :
A mixin class acts as the parent class, containing the desired functionality. A subclass can then inherit or simply reuse this functionality, but not as a means of specialization. Typically, the mixin will export the desired functionality to a child class, without creating a rigid, single "is a" relationship. Here lies the important difference between the concepts of mixins and inheritance, in that the child class can still inherit all the features of the parent class, but, the semantics about the child "being a kind of" the parent need not be necessarily applied.
In the above definition, I am not able to understand the statements marked in bold. what does it mean that
A subclass can inherit functionality in mixin but not as a means of specialization
In mixins, the child inherits all features of parent class but semantics about the child "being a kind" the parent need not be necessarily applied. - How can a child extend a parent and not necessarily a kind of Parent ? Is there an example like that.
I'm not sure I understood your question properly, but if I did, you're asking how something can inherit without really meaning the same thing as inheriting.
Mixins, however, aren't inheritance – it's actually more similar to dynamically adding a set of methods into an object. Whereas inheritance says "This thing is a kind of another thing", mixins say, "This object has some traits of this other thing." You can see this in the keyword used to declare mixins: trait.
To blatantly steal an example from the Scala homepage:
abstract class Spacecraft {
def engage(): Unit
}
trait CommandoBridge extends Spacecraft {
def engage(): Unit = {
for (_ <- 1 to 3)
speedUp()
}
def speedUp(): Unit
}
trait PulseEngine extends Spacecraft {
val maxPulse: Int
var currentPulse: Int = 0
def speedUp(): Unit = {
if (currentPulse < maxPulse)
currentPulse += 1
}
}
class StarCruiser extends Spacecraft
with CommandoBridge
with PulseEngine {
val maxPulse = 200
}
In this case, the StarCruiser isn't a CommandoBridge or PulseEngine; it has them, though, and gains the methods defined in those traits. It is a Spacecraft, as you can see because it inherits from that class.
It's worth mentioning that when a trait extends a class, if you want to make something with that trait, it has to extend that class. For example, if I had a class Dog, I couldn't have a Dog with PulseEngine unless Dog extended Spacecraft. In that way, it's not quite like adding methods; however, it's still similar.
A trait (which is called mixin when mixed with a class) is like an interface in Java (though there are many differences) where you can add additional features to a class without necessarily having "is a" relationship. Or you can say that generally traits bundle up features which can be used by multiple independent classes.
To give you an example from Scala library, Ordered[A] is a trait which provides implementation for some basic comparison operations (like <, <=, >, >=) to classes that can have data with natural ordering.
For example, let's say you have your own class Number and subclasses EvenNumber and OddNumber as shown below.
class Number(val num : Int) extends Ordered[Number] {
override def compare(that : Number) = this.num - that.num
}
trait Half extends Number {
def half() = num / 2
}
trait Increment extends Number {
def increment() = num + 1
}
class EvenNumber(val evenNum : Int) extends Number(evenNum) with Half
class OddNumber(val oddNum : Int) extends Number(oddNum) with Increment
In the example above, classes EvenNumber and OddNumber share is a relationship with Number but EvenNumber does not have "is a" relation with Half neither OddNumber share "is a" relation with Increment.
Another important point is even though class Number uses extends Ordered syntax, it means that Number has an implicit is a relationship with superclass of Ordered ie Any.
I think its very usage dependent. Scala being a multi-paradigm language makes it powerful as well as a bit confusing at times.
I think Mixins are very powerful when used the right way.
Mixins should be used to introduce behavior and reduce bolierplate.
A trait in Scala can have implementations and it is tempting to extend them and use them.
Traits could be used for inheritance. It can also be called mixins however that in my opinion is not the best way to use mixin behavior. In this case you could think of traits as Java Abstract Classes. Wherein you get subclasses that are "type of" the super class (the trait).
However Traits could be used as proper mixins as well. Now using a trait as a mixin depends on the implementation that is "how you mix it in". Mostly its a simple question to ask yourself . It is "Is the subclass of the trait truly a kind of the trait or are the behaviors in the trait behaviors that reduce boilerplate".
Typically it is best implemented by mixing in traits to objects rather than extending the trait to create new classes.
For example consider the following example:
//All future versions of DAO will extend this
trait AbstractDAO{
def getRecords:String
def updateRecords(records:String):Unit
}
//One concrete version
trait concreteDAO extends AbstractDAO{
override def getRecords={"Here are records"}
override def updateRecords(records:String){
println("Updated "+records)
}
}
//One concrete version
trait concreteDAO1 extends AbstractDAO{
override def getRecords={"Records returned from DAO2"}
override def updateRecords(records:String){
println("Updated via DAO2"+records)
}
}
//This trait just defines dependencies (in this case an instance of AbstractDAO) and defines operations based over that
trait service{
this:AbstractDAO =>
def updateRecordsViaDAO(record:String)={
updateRecords(record)
}
def getRecordsViaDAO={
getRecords
}
}
object DI extends App{
val wiredObject = new service with concreteDAO //injecting concrete DAO to the service and calling methods
wiredObject.updateRecords("RECORD1")
println(wiredObject.getRecords)
val wiredObject1 = new service with concreteDAO1
wiredObject1.updateRecords("RECORD2")
println(wiredObject1.getRecords)
}
concreteDAO is a trait which extends AbstractDAO - This is inheritance
val wiredObject = new service with concreteDAO -
This is proper mixin behavior
Since the service trait mandates the mixin of a AbstractDAO. It would be just wrong for Service to extend ConcreteDAO anyways because the service required AbstractDAO it is not a type of AbstractDAO.
Instead you create instances of service with different mixins.
The difference between mixin and inheritance is at semantic level. At syntax level they all are the same.
To mix in a trait, or to inherit from a trait, they all use extends or with which is the same syntax.
At semantic level, a trait that is intended to be mixed in usually doesn't have a is a relationship with the class mixining it which differs to a trait that is intended to be inherited.
To me, whether a trait is a mixin or parent is very subjective, which often time is a source of confusion.
I think it is talking about the actual class hierarchy. For example, a Dog is a type of Animal if it extends from the class (inheritance). It can be used wherever an Animal parameter is applicable.
Here is a simplification of my scenario that I am trying to make it work
// the UnrelatedN are mostly used as tag traits, for type-checking purposes
trait Unrelated1
trait Unrelated2
trait HasUnrelatedSupertrait {
type Unrelated // abstract type
}
trait HasUnrelated[... /*TODO: Parametrize with (factory of) UnrelatedN*/]
extends HasUnrelatedSupertrait {
type Unrelated = UnrelatedType // path-dependent type
implicit val unrelated = ... // instantiate or access (singleton) instance of Unrelated
}
trait Subtype1 extends HasUnrelated[/* Something involving Unrelated1 */] with ...
trait Subtype2 extends HasUnrelated[/* Something involving Unrelated2 */] with ...
// ... (many more similar subtypes)
Basically, I would like to inject the implicit val instance of
abstract type into (subtypes of) HasUnrelated in a non-intrusive
way, hopefully through a type parameter that I have some flexibility
over (see TODO).
(I don't care if Unrelated1/2 instances are constructed via new,
factory and how those factories are defined (as objects, classes
etc.), as long as I can get 2 distinct instances of Unrelated1/2.)
Some of the constraining factors why my attempts have failed are:
HasUnrelated and HasUnrelatedSupertrait must be traits, not classes
traits cannot have parameters (so I cannot pass (implicit) val factory)
traits cannot have context or view bounds (to bring in ClassTag/TypeTag)
I am not willing to clutter all the subtypes of HasUnrelated with
additional type/val declarations
However, I am willing to do one or more of the following changes:
introduce (singleton) factories for Unrelated1/2
introduce arbitrary inheritance in Unrelated1/2 as long as those
types are still unrelated (neither is subtype of the other)
add supertype to HasUnrelated as long is it requires extra
declarations (if any) only in HasUnrelated, but not any of its subtypes
Is there a way to achieve this in Scala and if so how?
Probably type class is something you are looking for? Consider this example
trait Companion[T] {
val comp: T
}
object Companion {
def apply[T: Companion] = implicitly[Companion[T]]
}
object UnrelatedType {
implicit val thisComp =
new Companion[UnrelatedType.type] {
val comp = UnrelatedType
}
}
// Somewhere later
type Unrelated = UnrelatedType
implicit val unrelated = Companion[UnrelatedType]
Scala 2.10 introduces value classes, which you specify by making your class extend AnyVal. There are many restrictions on value classes, but one of their huge advantages is that they allow extension methods without the penalty of creating a new class: unless boxing is required e.g. to put the value class in an array, it is simply the old class plus a set of methods that take the class as the first parameter. Thus,
implicit class Foo(val i: Int) extends AnyVal {
def +*(j: Int) = i + j*j
}
unwraps to something that can be no more expensive than writing i + j*j yourself (once the JVM inlines the method call).
Unfortunately, one of the restrictions in SIP-15 which describes value classes is
The underlying type of C may not be a value class.
If you have a value class that you can get your hands on, say, as a way to provide type-safe units without the overhead of boxing (unless you really need it):
class Meter(val meters: Double) extends AnyVal {
def centimeters = meters*100.0 // No longer type-safe
def +(m: Meter) = new Meter(meters+m.meters) // Only works with Meter!
}
then is there a way to enrich Meter without object-creation overhead? The restriction in SIP-15 prevents the obvious
implicit class RichMeter(m: Meter) extends AnyVal { ... }
approach.
In order to extend value classes, you need to recapture the underlying type. Since value classes are required to have their wrapped type accessible (val i not just i above), you can always do this. You can't use the handy implicit class shortcut, but you can still add the implicit conversion longhand. So, if you want to add a - method to Meter you must do something like
class RichMeter(val meters: Double) extends AnyVal {
def -(m: Meter) = new Meter(meters - m.meters)
}
implicit def EnrichMeters(m: Meter) = new RichMeter(m.meters)
Note also that you are allowed to (freely) rewrap any parameters with the original value class, so if it has functionality that you rely on (e.g. it wraps a Long but performs complicated bit-mixing), you can just rewrap the underlying class in the value class you're trying to extend wherever you need it.
(Note also that you'll get a warning unless you import language.implicitConversions.)
Addendum: in Scala 2.11+, you may make the val private; for cases where this was done, you will not be able to use this trick.
General style question.
As I become better at writing functional code, more of my methods are becoming pure functions. I find that lots of my "classes" (in the loose sense of a container of code) are becoming state free. Therefore I make them objects instead of classes as there is no need to instantiate them.
Now in the Java world, having a class full of "static" methods would seem rather odd, and is generally only used for "helper" classes, like you see with Guava and Commons-* and so on.
So my question is, in the Scala world, is having lots of logic inside "objects" and not "classes" quite normal, or is there another preferred idiom.
As you mention in your title, objects are singleton classes, not classes with static methods as you mention in the text of your question.
And there are a few things that make scala objects better than both static AND singletons in java-world, so it is quite "normal" to use them in scala.
For one thing, unlike static methods, object methods are polymorphic, so you can easily inject objects as dependencies:
scala> trait Quack {def quack="quack"}
defined trait Quack
scala> class Duck extends Quack
defined class Duck
scala> object Quacker extends Quack {override def quack="QUAACK"}
defined module Quacker
// MakeItQuack expects something implementing Quack
scala> def MakeItQuack(q: Quack) = q.quack
MakeItQuack: (q: Quack)java.lang.String
// ...it can be a class
scala> MakeItQuack(new Duck)
res0: java.lang.String = quack
// ...or it can be an object
scala> MakeItQuack(Quacker)
res1: java.lang.String = QUAACK
This makes them usable without tight coupling and without promoting global state (which are two of the issues generally attributed to both static methods and singletons).
Then there's the fact that they do away with all the boilerplate that makes singletons so ugly and unidiomatic-looking in java. This is an often overlooked point, in my opinion, and part of what makes singletons so frowned upon in java even when they are stateless and not used as global state.
Also, the boilerplate you have to repeat in all java singletons gives the class two responsibilities: ensuring there's only one instance of itself and doing whatever it's supposed to do. The fact that scala has a declarative way of specifying that something is a singleton relieves the class and the programmer from breaking the single responsibility principle. In scala you know an object is a singleton and you can just reason about what it does.
You can also use package objects e.g. take a look at the scala.math package object here
https://lampsvn.epfl.ch/trac/scala/browser/scala/tags/R_2_9_1_final/src//library/scala/math/package.scala
Yes, I would say it is normal.
For most of my classes I create a companion object to handle some initialization/validation logic there. For example instead of throwing an exception if validation of parameters fails in a constructor it is possible to return an Option or an Either in the companion objects apply-method:
class X(val x: Int) {
require(x >= 0)
}
// ==>
object X {
def apply(x: Int): Option[X] =
if (x < 0) None else Some(new X(x))
}
class X private (val x: Int)
In the companion object one can add a lot of additional logic, such as a cache for immutable objects.
objects are also good for sending signals between instances if there is no need to also send messages:
object X {
def doSomething(s: String) = ???
}
case class C(s: String)
class A extends Actor {
var calculateLater: String = ""
def receive = {
case X => X.doSomething(s)
case C(s) => calculateLater = s
}
}
Another use case for objects is to reduce the scope of elements:
// traits with lots of members
trait A
trait B
trait C
trait Trait {
def validate(s: String) = {
import validator._
// use logic of validator
}
private object validator extends A with B with C {
// all members of A, B and C are visible here
}
}
class Class extends Trait {
// no unnecessary members and name conflicts here
}
I'm creating some parameterized classes C[T] and I want to make some requirements of the characteristics of the type T to be able to be a parameter of my class. It would be simple if I just wanted to say that T inherited from traits or classes (as we do with Ordering). But I want it to implement some functions as well.
For example, I've seen that many pre-defined types implement MinValue and MaxValue, I would like my type T to implement these too. I've received some advice to just define an implicit function. But I wouldn't like that all the users were obliged to implement this function for these when it is already implemented. I could implement them at my code too, but it seems just to be a poor quick fix.
For example, when defining heaps, I would like to allowd users to construct a empty Heap. In these cases I want to inicialize value with the minimum value the type T could have. Obviously this code does not works.
class Heap[T](val value:T,val heaps:List[Heap[T]]){
def this()=this(T.MinValue,List())
}
I also would love to receive some advice about really good online Scala 2.8 references.
A bunch of things, all loosely related by virtue of sharing a few methods (though with different return types). Sure sounds like ad-hoc polymorphism to me!
roll on the type class...
class HasMinMax[T] {
def maxValue: T
def minValue: T
}
implicit object IntHasMinMax extends HasMinMax[Int] {
def maxValue = Int.MaxValue
def minValue = Int.MinValue
}
implicit object DoubleHasMinMax extends HasMinMax[Double] {
def maxValue = Double.MaxValue
def minValue = Double.MinValue
}
// etc
class C[T : HasMinMax](param : T) {
val bounds = implicitly[HasMinMax[T]]
// now use bounds.minValue or bounds.minValue as required
}
UPDATE
The [T : HasMinMax] notation is a context bound, and is syntactic sugar for:
class C[T](param : T)(implicit bounds: HasMinMax[T]) {
// now use bounds.minValue or bounds.minValue as required
}
You can either use type bounds:
trait Base
class C[T <: Base]
enabling C to be parametrized with any type T which is a subtype of Base.
Or you can use implicit parameters to express requirements:
trait Requirement[T] {
def requiredFunctionExample(t: T): T
}
class C[T](implicit req: Requirement[T])
Thus, objects of class C can only be constructed if there exists an implementation of the Requirement trait for the type T you wish to parametrize them with. You can place implementations of Requirement for different types T in, for instance, a package object, thus bringing them into scope whenever the corresponding package is imported.