w3hello.com logo
Home PHP C# C++ Android Java Javascript Python IOS SQL HTML videos Categories
Force Scala trait to implement a certain method
You can do the following: class A extends B with C { super[B].foo() } This will only compile if B implements foo. Use with caution though as it (potentially) introduces some unintuitive coupling. Further, if A overrides foo, still B's foo will be called. One IMHO valid use case is conflict resolution: trait B { def foo() = println("B") } trait C { def foo() = println("C") } class A extends B with C { override def foo() = super[B].foo() } If you want to make sure B declares foo, you can use type ascription: class A extends B with C { (this:B).foo() } This will only compile if B declares foo (but it might be implemented in C or A).

Categories : Scala

How to share an item between derived classes of a trait in Scala?
Leaving aside considerations whether maintaining global state is a good idea; you can use a singleton object: object Foo { var state = 0 } trait Foo class Bar extends Foo { Foo.state += 1 } class Baz extends Foo { Foo.state -= 1 }

Categories : Scala

Scala Reflection - Loading or finding classes based on trait
This is what ServiceLoader is for. I think the reflection API does make it easier to sort out what you need (i.e., for filtering but not for querying the class loader). If, by your phrase, "searching the loaded classes", you really mean classes that are already loaded, see this question for getting them. You could imagine a widgets library with an initializer that just ensures that all the widget classes it knows about are loaded. Then the client only needs to know the initializer. The type test is the same. val need = typeOf[Whatsit[Cog]] for (x <- (ServiceLoader load classOf[Whatsit[_]]).asScala) { val im = currentMirror reflect x if (im.symbol.toType weak_<:< need) Console println s"$x is what I need" else Console println s"$x is not what I need, I'm lookin

Categories : Scala

Json Serialization for Trait with Multiple Case Classes (Sum Types) in Scala's Play
I think that is about as simple as you can make it, if you want to avoid writing the code for each explicit subtype maybe you could do it with reflection, use jackson directly or some other json library with reflection support. Or write your own macro to generate the Format from a list of subtypes.

Categories : Json

Scala trait naming convention when trait is the same as class
When there's only likely to ever be 1 implementation of a trait, it makes sense to use the "Impl" convention: trait = Foo and class = FooImpl. Though I've never really been a fan of this convention because it's kind of limiting to one implementation, it sounds like that's exactly what I need here. When more classes implement an interface/trait, it's more likely that naming each implementation will flow more naturally.

Categories : Scala

specifying trait constraint in scala
The problem with your code is more fundamental than just missing a type constrait on L to specify it's a trait. Even if you could do that, what should the compiler do? When using the new operator, the type must be fully known, but here L is an abstract type so new BaseLayer with L is entirely unknown at the point of you call new. There is thus no way for the compiler to know what to do here. What you should do is simply to make layer abstract, and let the concrete sub-classes perform the instantation. trait Layer{ def write(s: String): String } trait TimeStampLayer extends Layer{ abstract override def write(s: String) = System.nanoTime + super.write(s) } trait BaseLayer extends Layer { def write(s: String) = s } abstract class LayerTest { type L <: Layer val layer: L /

Categories : Scala

Scala trait syntax
That is called a "self-type annotation" and it requires that any use of trait DatabaseSessionSupport in an instantiable class must be accompanied by ("mixed in with") a type consistent with ScalatraBase. I have not looked at this specific code, but it is most likely a use of the so-called "Cake Pattern." You can find many treatments of this concept both in Stack Overflow, in various blogs and in a classic paper by Odersky et. al. titled "Scalable Component Abstractions."

Categories : Scala

Scala: How to inherit the same trait twice?
Unfortunately you can't inherit from the same trait twice. Instead you should use some other mechanism. For instance, Reverse and Echo are both manipulations of the waveform. You could have val reverse = (w: Waveform) => // produce a reverse waveform val echo = (w: Waveform) => // copy the waveform onto itself with delay new SoundFile("myFile.wav", reverse andThen echo andThen reverse) or somesuch. If you require more changes than just a simple function, you'll have to encapsulate the modifications to functionality in your own class: trait Transform { self => def apply(w: Waveform): Waveform def time: Double def andThen(t: Transform) = new Transform { def apply(w: Waveform) = t(self(w)) def time = self.time + t.time } } val reverse = new Transform { def

Categories : Scala

How do you cast super in a Scala trait?
Sometimes the compiler is right when it is convinced that we don't know what we're doing. I'm not sure what you mean by "there is no concrete implementation." Normally, abstract override means you'll be mixed in with a class that has a concrete implementation. Otherwise, there would be nothing to invoke. Possibly, you mean, "I have a class with InheritableTrait, and I want to extend it and mix in InheritableTrait again." But actually, you can't do that. Your mix-ins are linearized once. There was a recent question with a great answer, which I'll try to find for you. And maybe we can mark this as dupe. Update: here's a similar recent question which may help answer or help improve your question. It includes a fine and thorough answer, though frankly I prefer the other answer which

Categories : Scala

scala override trait with generic method
You are changing the signature of the method, so it is not a legal override, it would break polymorphism. You must either parametrize the Converter trait or use another method name. You can, however, receive a Base object and cast it, but it is not recommended practice since it may result in an exception at runtime: object ConverterBaseOne extends Converter { override def toAClass[T <: Base](e: T): AClass = { printf(e.asInstanceOf[BaseOne].b) // ... } }

Categories : Scala

OOP abstract classes when to implement abstract methods
Generally, you should implement all methods in the last common ancestor. So if you want your children classes will behave the same way, implement them now. If they are to be implemented, but in many ways by different classes, leave them abstract. Actually, an abstract class is done only for requiring that if somebody will inherit something from this common class, he will provide these methods (abstract class is something similar to interface). If you implement all of them, there is no need to use an abstract class.

Categories : PHP

Haskell-like type-constrained trait implementation in Scala (?)
The type class pattern in Scala works like this: trait Serializable[-T] { def toDifferentString(v: T): String } class SerializableTree[T : Serializable] extends Serializable[Tree[T]] { def toDifferentString(t: Tree[T]) = t match { case Leaf() => "" case Node(v, left, right) => val vStr = implicitly[Serializable[T]].toDifferentString(v) val lStr = toDifferentString(left) val rStr = toDifferentString(right) s"Node($vStr, $lStr, $rStr)" } } object SerializableTree { implicit def st[T : Serializable]: Serializable[Tree[T]] = new SerializableTree[T] } Type classes in Scala are implemented as a pattern, where the type class provides one or more methods that take as one of their parameters the class for which they are providing these methods. T

Categories : Scala

correct type specification for cloneable-like trait in scala
Scala type variance allows to you implement what you need in a simple way, but you have to move away from inheritance and go to typeclasses. trait Cloner[A]{ def cloneObject(input:A):A } trait CloningFunctions{ def cloneObject[A](input:A)(implicit cloner:Cloner[A]) = cloner.cloneObject(input) } object CloningFunctions extends CloningFunctions class MyClass1(val b:Int) class MyClass2(val a:Int,b:Int) extends MyClass1(b) object Example { implicit val cloner = new Cloner[MyClass1]{ def cloneObject(input: MyClass1): MyClass1 = new MyClass1(input.b) } import CloningFunctions._ cloneObject(new MyClass2(3,4)) } The idea here is that since Cloner[A] is invariant in type A, the following code won't compile: could not find implicit value for parameter cloner: Cloner[MyCla

Categories : Scala

Scala trait same method and argument with different return types
On the JVM the return type of a method is not a part of a method signature. You have to give different method names or parameters. From Oracle Docs: Definition: Two of the components of a method declaration comprise the method signature—the method's name and the parameter types. What you are tryng to do is called Method overloading and Oracle says the following: The compiler does not consider return type when differentiating methods, so you cannot declare two methods with the same signature even if they have a different return type. Cause Scala also compiles to JVM byte code, rules are the same

Categories : Scala

Override a trait method for final class in Scala
Method resolution rules are different in the two cases. In the first case an anonymous class is constructed first by whatever happens to be the methods/attributes of the type: final class TestClass with TestTrait and then you are trying to override a method of that, which conflicts with the final qualifier of TestClass. In the second case you explicitly specify that you are overriding TestTrait behavior, and then the overriden behavior is mixed into TestClass. I think it's perfectly fine to use the second method, and that it conveys more clearly what the intention is.

Categories : Scala

Does trait in Scala eliminate the need of adding behaviour through dependency injection?
Why, yes. It is known as the "cake pattern", and it can handle things much more complex than you might think. In fact, it supports modularity at a level found in very few other languages. There are plenty of information about it on the web, but I suggest the excellent presentation by Daniel Spiewak and NEScala 2013, Cake Pattern Bakery from The Black Lagoon, as a starting point.

Categories : Scala

Serialization of case classes extending Seq-Trait
Without discussing why such a class is useful... How would you manually encode such object? In JSON you can have dictionaries and lists, so you cannot expect a list to have extra named attributes. You can make your IntSeq class to have a list attribute and not extend Seq itself (and maybe provide an automatic conversion), so your JSON could look like: {'length' : 5, 'ints' : [1, 2, 3, 4, 5]}

Categories : Json

How to correctly override (implement) method defined in parameterized super trait?
Your update method is parametrized with a type T that happens to have the same name as the type parameter of your class. Your trait Check is equivalent to this: trait Check[T] { def complete() : Boolean = ... def passed() : Boolean = ... def update[U]( data : U ) : Unit } Whereas you probably wanted this: trait Check[T] { def complete() : Boolean = ... def passed() : Boolean = ... def update( data : T ) : Unit }

Categories : Scala

Eta-expansion between methods and functions with overloaded methods in Scala
Implicit is the correct term, and the section is 6.26.2 in the spec, and this must be a duplicate question (or so one would think; this is stable behavior). The linked question also answers that the expected type must be a function. I'll go out on a limb and say that when overloaded, applicability is undermined because there is no expected type (6.26.3, infamously). When not overloaded, 6.26.2 applies (eta expansion) because the type of the parameter determines the expected type. When overloaded, the arg is specifically typed with no expected type, hence 6.26.2 doesn't apply; therefore neither overloaded variant of d is deemed to be applicable. From 6.26.3 Overloading Resolution Otherwise, let S 1 , . . . , S m be the vector of types obtained by typing each argument with an u

Categories : Function

Alternative to static nested classes in C# for grouping a classes public methods?
Employee theEmployee = new Employee(); Would give you an Employee object to work with. With this you could change the values of the Employee class from DataBaseHandler

Categories : C#

Referencing vals in method returning new trait instance inside trait
The following works because Side.this does not refer to the anonymous class under construction. Anonymity has its privileges. scala> :pa // Entering paste mode (ctrl-D to finish) trait Side { val offset: Int def +(side: Side) = new Side { val offset = Side.this.offset + side.offset } } // Exiting paste mode, now interpreting. defined trait Side scala> new Side { val offset = 1 } res0: Side = $anon$1@7e070e85 scala> new Side { val offset = 2 } res1: Side = $anon$1@5f701cd1 scala> res0+res1 res2: Side = Side$$anon$1@188ef927 scala> .offset res3: Int = 3 First guess, thinking it was a shadowing problem: scala> :pa // Entering paste mode (ctrl-D to finish) trait Side { val offset: Int def +(side: Side) = new { val offset = Side.this.offset + sid

Categories : Scala

Trait A can only be extended by class that extends Trait B
Just specify what you want this to be: trait B { this: A => def bar = this.foo } This is so called self type and this here is an alias rather than keyword (so self: A, that: A and so on are perfectly legal).

Categories : Scala

How to solve "Implementation restriction: trait ... accesses protected method ... inside a concrete trait method."
The problem is that even though the trait extends the Java class, the implementation is not actually in something that extends the Java class. Consider class A { def f = "foo" } trait T extends A { def g = f + "bar" } class B extends T { def h = g + "baz" } In the actual bytecode for B we see public java.lang.String g(); Code: 0: aload_0 1: invokestatic #17; //Method T$class.g:(LT;)Ljava/lang/String; 4: areturn which means it just forwards to something called T$class, which it turns out is public abstract class T$class extends java.lang.Object{ public static java.lang.String g(T); Code: ... So the body of the code isn't called from a subclass of A at all. Now, with Scala that's no problem because it just omits the protected flag from bytecode. But Java e

Categories : Scala

How to implement "or" in a scala filter?
You can only use the placeholder syntax if the parameter appears only once in the function expression. Otherwise, you have to declare the function parameter explicitly: list.filter(x => x % 3 == 0 || x % 5 == 0) Multiple placeholders expand to multiple method parameters.

Categories : Scala

How does Scala implement return from within an expression?
The foo example depends on which of def process(s: String): String def process(s: => String): String it is. I'm assuming the former, since you suggest process isn't run. This is just the way it always works when passing an argument--you do the argument-creation work first, then call the method. Since you run into a return, it's easy: you just call the appropriate return from bytecode while creating the argument*, and never go on to invoke the method. So it is just a local return. The find example is a little more involved. Let's try a maximally simple example motivated by a foo which requires a nonlocal return: class Nonlocal { def pr(s: => String) = { println(s); "Printed" } def foo(x: AnyRef): String = pr(x match { case (s: String) => s; case _ =

Categories : Scala

Implement transaction aspect in Scala
Method tx accepts function of 1 argument as parameter and method saveMyEntity accepts no arguments, so you can't use it as A => B (function of 1 argument). You are not using a and f separately, so there is no need in a. You could use by-name parameters here: def tx[B](f: => B): B = { If you want to use a saveMyEntity as Unit => Unit you should create function explicitly: tx[Unit, Unit](_ => saveMyEntity)(()) I guess some changes may improve your code readability: import util.control.Exception.allCatch def withSession[T](f: Session => T):T = { val session = ??? // start session here allCatch.anfFinally{ session.close() } apply { f(session) } } def inTransaction[T](f: => T): T = withSession{ session => session().beginTransaction() try {

Categories : Scala

Trying to implement a Circular Enumeration in Scala
I believe I can get it to work with the following changes - modify the return type of nextValue: def nextValue(value: Value): CircularEnumeration.this.Value = { and the last line (returned value) to: value_withmath.asInstanceOf[CircularEnumeration.this.Value] Then, defining MyEnumeration as: scala> object MyEnumeration extends CircularEnumeration { | type MyEnumeration = Value | val Zero, One, Two, Three, Four = Value | } defined module MyEnumeration we get: scala> MyEnumeration.nextValue(MyEnumeration(3)) res0: MyEnumeration.Value = Four scala> MyEnumeration.nextValue(MyEnumeration(4)) res1: MyEnumeration.Value = Zero

Categories : Scala

inherit prototype methods from other classes without overriding own prototype methods
The best example I can think of comes from: http://robertnyman.com/2008/10/06/javascript-inheritance-how-and-why/ function Being() { this.living = true; this.breathes = function () { return true; }; } function Robert() { // Robert.prototype = new Being(); /* edit */ this.blogs = true; this.getsBored = function () { return "You betcha"; }; } Robert.prototype = new Being(); Robert.prototype.newMethod = function() { console.log('new method executed'); return this; } Note this example, has been updated, the first comment below is directed at the first code I had up, which contained the prototype inside the Robert method.

Categories : Javascript

Scala right associative methods
From the spec (section 1.1): There are three ways to form an identifier. First, an identifier can start with a letter which can be followed by an arbitrary sequence of letters and digits. This may be followed by underscore ‘_’ characters and another string composed of either letters and digits or of operator characters. Second, an identifier can start with an operator character followed by an arbitrary sequence of operator characters. The preceding two forms are called plain identifiers. Finally, an identifier may also be formed by an arbitrary string between back-quotes (host systems may impose some restrictions on which strings are legal for identifiers). The identifier then is composed of all characters excluding the backquotes themselves. So it looks like

Categories : Scala

How to implement the `List` monad transformer in Scala?
I am not quite sure, what the Step means in scalaz, but implementing a ListT is pretty straight forward. Depending on how many operations you want to put on it, it can be a little work, but the basic monad operations can be implemented as follows. First we need typeclasses for monad and functor (we could also add applicative, but that is not necessary for this example): trait Functor[F[_]] { def map[A,B](fa: F[A])(f: A => B): F[B] } trait Monad[F[_]] extends Functor[F] { def flatMap[A,B](fa: F[A])(f: A => F[B]): F[B] def pure[A](x: A): F[A] } object Monad { implicit object ListMonad extends Monad[List] { def map[A,B](fa: List[A])(f: A => B) = fa map f def flatMap[A,B](fa: List[A])(f: A => List[B]) = fa flatMap f def pure[A](x: A) = x :: Nil } impli

Categories : Scala

Generic way to implement a Pk Writes in Play Scala
The only thing you need to do is ensuring that there is deserializer for type E in scope, because now you can't be sure that each type you use is writeable. You can try it: class Value[A](value: A){ def get[A] = value } implicit def valueWrites[E](implicit longWrites: Writes[E]) = new Writes[Value[E]]{ def writes(value: Value[E]): JsValue = Json.toJson(value.get) } Json.toJson(new Value(5L)) You can shorten implicit method to: implicit def valueToJson[E: Writes] = new Writes[Value[E]]{ def writes(value: Value[E]): JsValue = Json.toJson(value.get) } Edit: These two methods above are exactly the same, it means that method needs implicit value, in your case Pk[Long], so this method knows how to deserialize number. In other words, E: Writes tells the method: search for imp

Categories : Scala

Using Lenses on Scala Regular Classes
It seems to be that, by defining a copy function (unfortunately by hand), regular classes can work with lenses, as Travis mentioned in his comment to the question, above. Below is a proof of concept that works (using json4s and a copy of an old Scalaz lens implementation, borrowed from Daniel Sobral's answer to Cleaner way to update nested structures): import org.json4s._ import org.json4s.JsonDSL._ import org.json4s.native.JsonMethods._ import native.Serialization.write class Parent(val name:String, val age:Int, val kids:List[Kid]){ override def toString() = s"""$name is $age years old, her/his kids are ${kids.mkString(", ")}.""" def copy(name:String = name, age:Int = age, kids:List[Kid] = kids) = new Parent(name, age, kids) } class Kid(val name:String, val age:Int){ overr

Categories : Scala

Use case classes as messages in Scala
You have 2 different classes with the same name CreateTS. You are sending CreateTS defined in sender and trying to receive message of other type with the same name in receiver. You should move declarations of case classes from method body so it will be in scope of both methods. Note that scala actors are deprecated, you should use akka actors.

Categories : Scala

Get hostname and pid in scala without using java classes?
If you run on the JVM, as Scala does, you're JVM-reliant. The Java libs are the canonical way to interact with the JVM to fetch such information, so you should use them. Scala does not provide an alternative, and any alternative that was provided would likely be less reliable as Typesafe does not have the resources that Sun/Oracle/IBM/etc. did/does. It does mean that if you use an experimental or hobby-level JVM that you may be out of luck getting your host name. (You can always spawn an external process and use a Linux command-line utility, if your JVM supports that, of course, but don't expect that to be terribly portable.)

Categories : Scala

Adding methods to a list in Scala
this is not a correct syntax () => println("x") :: l2 the correct one is (() => println("x")) :: l2 and why l2 = foo :: l2 does not compile is because the type of foo does not compliant with l2 to understand it deeply try following foo.toString however followings will be compiled var fn = {() => println("y")} l2 = fn :: l2 or foo _ :: l2

Categories : Scala

Scala MongoDB Chaining Methods
You could try to use an implicit value class to enrich the MongoCursor: object ImplicitClassContainer { implicit class RichMongoCursor(val mc: MongoCursor) extends AnyVal { def sort(sortFun: DBObject): MongoCursor = mc.sort(sortFun) def limit(number: Int): MongoCursor = mc.limit(number) def offset(number: Int): MongoCursor = mc.skip(number) } } to be used like this import ImplicitClassContainer._ def x(mc: MongoCursor): MongoCursor = { mc.offset(25).limit(25) } Basically it's the same pattern which is used to add functionality to Array: You get additional functions in "flow style", but it's still a MongoCursor. As it is an implicit value class, no additional instance of an object is created at run-time.

Categories : Mongodb

Traits for "static" methods in Scala?
Maybe things that extend B don't want to keep re-importing A? Maybe the method relies upon other "static" methods but you actually want to override the implementation? If B is final (or an object) and the methods really are static (and don't refer to implementations that you might want to change in B), then there's not much point in mixing in a trait. The only exception is if there are implicit conversions defined, where if you mix in the implicit it will have lower priority than if you declare it yourself. (Check out scala.LowPriorityImplicits which is mixed into scala.Predef for examples.)

Categories : Scala

Using @BeanProperty or Create Set & Get methods using scala
In functional programming and Scala in general you should always prefer immutable objects. But if you need to change the object state, then i would stick to (g|s)etters. Cause in this case you can without changing the internal state of the object return a new object with modified state. class MyClass(val name) { def setName(newName: String) = new MyClass(newName) } This way preserves immutability and gives you setters: setName(String) and getters: obj.name @BeanPropery is used when you need high level of interoperability with some Java code, it helps you quickly generate (g|s)etters for your code, but it has some constraints cause you cannot give the names to this methods which you would like. Although i recomend to use case classes with copy method: case class Person(name: String,

Categories : Spring

How to use methods from other classes?
are you trying to use the property getters/setters?(you seem to be using the setters just fine) Just treat them as variables Console.WriteLine("Längd : " + rectangle.langden.ToString() ); or Console.WriteLine("Längd : {0}", rectangle.langden );

Categories : C#

How should you implement STL features for custom classes?
Recall that there ain't no such thing as a partial specialization of function templates. So you can't partially specialize std::tuple_element et al for your class. Normally, you would define free-standing functions that are logically part of your class' interface in the same namespace as the class itself. Then you can rely on argument-dependent lookup to find them. std::get would be found by that same mechanism - users of your library will not in fact be forced to write using std::get.

Categories : C++



© Copyright 2017 w3hello.com Publishing Limited. All rights reserved.