Menu
  • HOME
  • TAGS

How to configure Laravel model attributes in a trait?

laravel,model,attributes,eloquent,trait

You could override the method where $this->hidden is actually used. And that's getArrayableItems trait Multilingual { protected function getArrayableItems(array $values) { if(!in_array('translation_of', $this->hidden)){ $this->hidden[] = 'translation_of'; } return parent::getArrayableItems($values); } } ...

How to implement a trait for any mutability?

rust,trait,mutability

Can mutability be a generic parameter in traits? No. ^_^ Here's some detailed discussion on the matter (Forum, Reddit). I think in general people recognize that the current state is not ideal, but that it's not terribly constraining at the moment, either. There's concerns on exactly how it would...

Using sealed trait as a key for a map

scala,trait

Because Map needs the keys to have properties which are defined in Product and Serializable, so Scala implicitly creates anonymous class which extends your class with Product and Serializable which provides default implementations of equals and hash. object Test extends App { trait PS extends Product with Serializable sealed trait...

Scala - aliasing a type inside a type

scala,trait

The . operator with types in Scala is used for path-dependent types. For example, your f.Bar is an instance of Bar that has f as its parent. The compiler forbids (new Foo).Bar because it isn't a useful expression - you throw away the only Foo that can be used to...

Type definition with a trait: Differences of specifying an explicit lifetime bound?

types,rust,trait

Answer for new question You really have two orthogonal cases. I'll tackle the easier one first, the difference of #2 and #3. Comments are inline with what I hope is a representative example: trait Kind { fn trait_fn(&self) -> u8 { 0 } } type CollectionOfKind1<'a> = Vec<&'a (Kind +...

What is the difference between trait and behavior in cakephp 3?

behavior,cakephp-3.0,trait

One is a PHP language construct, the other is a programmatic concept. You may want to read upon what traits are, so that you understand that this question, as it stands, doesn't make too much sense. Also stuff like "doesn't work" doesn't serve as a proper problem description, please be...

Get Namespace of an object using an Abstract Class or Trait?

php,oop,namespaces,abstract-class,trait

Use the reflection api: var_dump((new \ReflectionObject($this))->getNamespaceName()); This is the kind of thing it's made for....

Type variance in multiple type instances of traits

scala,generics,multiple-inheritance,covariance,trait

If you see the compiler actually explains it well: : Foo1[String] with Foo2[String]> inherits different type instances of trait Foo: Foo[Nothing,String] and Foo[String,Nothing] new Foo1[String] with Foo2[String] To explain first one: new Foo1[String] with Foo2[Nothing] look at this example: scala> val x = new Foo1[String] with Foo2[Nothing] x: Foo1[String] with...

Argument 1 passed to Foo::__construct() must be an instance of Psr\Log\LoggerTrait, instance of Mock_Trait_LoggerTrait_65811a25_bdddd884 given

php,unit-testing,mocking,phpunit,trait

You can't type hint traits. Your type hint is looking for a class of type \Psr\Log\LoggerTrait. It appears that it is actually a trait and not an object. http://php.net/manual/en/language.oop5.typehinting.php The getMockForTrait method is used to create a concrete object of the trait so that you can test the traits functionality....

StackoverFlow error on trait creating self object

scala,trait

You have a cyclic condition here. User extends userTrait (which intern initializes new User ...)

How to import identity operations in scalaz?

scala,scalaz,trait

https://github.com/scalaz/scalaz/blob/v7.1.2/core/src/main/scala/scalaz/syntax/Syntax.scala#L117 You can use scalaz.syntax.id instead of new scalaz.syntax.ToIdOps{} import scalaz.syntax.id._ ...

Java 8 default methods as traits : safe?

java,java-8,trait,default-method

The short answer is: it's safe if you use them safely :) The snarky answer: tell me what you mean by traits, and maybe I'll give you a better answer :) In all seriousness, the term "trait" is not well-defined. Many Java developers are most familiar with traits as they...

Java's TimerTask run() function not called when calling trait function inside

java,scala,timer,timertask,trait

I got it to work. I changed the code to this: trait IntervalUpdate { val updateInterval: Long def onUpdateTask:() => Unit val timer: Timer = new Timer() val timerTask = new TimerTask { override def run(): Unit = onUpdateTask() } timer.scheduleAtFixedRate(timerTask, updateInterval, updateInterval) } ...

Scala - How to save Trait's names in a collection?

scala,trait

You can make compiler enforce these rules for you. Consider this: trait Base { def kind: String } trait Bonus extends Base { override def kind = "bonus" } trait Discount extends Base { abstract override def kind = "discount" } trait Order { self: Bonus => } new Order...

Scala: Class with traits whose constructor takes another class with a parallel set of traits?

scala,class,constructor,multiple-inheritance,trait

You can simulate this with traits and companion objects with apply methods. trait A trait Ax extends A { def doAx = "Ax method" } trait Ay extends A { def doAy = "Ay method" } trait B { val a: A } object B { def apply(aa: A): B...

How to constrain type as abstract type member in trait?

scala,types,trait

If you want to require a Monad[M] instance, just... require it: trait C { type M[_] /*implicit if you like*/ def m: Monad[M] ... } Implementing classes will unfortunately have to specify m, if only as val m = implicitly; the only way around that is the abstract class approach...

Why can't I pass a trait to a Scala function and call it: response[A: T](r: A) = { r(value) }

scala,higher-order-functions,trait

Ah... OK, figured it out. Apparently I have to call the apply() method directly, as in instance.apply(...) which is a bit startling, but it works: trait GPResponse { abstract def apply(error: GPError): GPResponse } trait GPResponseMapping { def response(error: Int, instance: GPResponse) = { (resultCodeFor(error), instance.apply(error)) } ... If anyone...

How can an object in Scala be cast to the intersection of its own type and any unrelated trait?

scala,types,casting,trait

The problem is that JVM doesn't support intersection types, so there is no obvious runtime equivalent to asInstanceOf[Int with Foo]. This is basically the same issue as asInstanceOf[T], where T is a generic parameter (both in Scala and equivalent Java): you also have the cast which appears to succeed at...

PHP Reflection: How to know if a method/property/constant is inherited from trait?

php,inheritance,reflection,traits,trait

Important notes This is only because of "academical" interest, in real situation you should not care about - from where method was derived as it contradicts the idea of traits, e.g. transparent substitution. Also, because of how traits are working, any kind of such manipulations might be considered as "hacky",...

Laravel 5 entrust attachRolle

laravel,trait

The problem is not the call to attachRole() itself but on what you are calling it. $user is not a model but a collection. You probably just have to switch out get() with first() in the query that fetches your user. Something like: $user = User::where(...)->first(); $user->attachRole($owner); ...

trait with functions that return an iterator

iterator,rust,trait

Rust's libstd has one implementation of this, the trait IntoIterator. /// Conversion into an `Iterator` pub trait IntoIterator { /// The type of the elements being iterated type Item; /// A container for iterating over elements of type `Item` type IntoIter: Iterator<Item=Self::Item>; /// Consumes `Self` and returns an iterator over...

Scala self-typed trait and calling method on supertype

scala,trait

You are looking for abstract override modifier, but to use it you need explicitly extend the Job class, then in you trait you can use members of your superclass: class Job(args:String) { def config:Map[String,String] = Map.empty } trait ExtraConfig extends Job { abstract override def config = super.config ++ Map("extra"...

How to initialize trait's vals in subtrait?

scala,trait

By section 5.1 of the Scala specification, super classes are initialized first. Even though vals cannot normally be reinstantiated, they do start with a default initial value during construction. You can either use def, which has different semantics: trait MessagePrinter { def message: String println(message) } class HelloPrinter extends MessagePrinter...

How to ensure custom order of traits upon mixing them in?

scala,trait

No, you can just declare trait to be mixed with other types, like this: trait B trait A { this: B => } With this, trait A is only allowed to be mixed in to types with trait B mixed in....

Implementing a trait for a trait

rust,trait

The issue is not with Sized. The syntax you're looking for is: impl<T: Measurement> Add for T { ... } instead of: impl Add for Measurement { ... } Because the right-hand side of the for must be an object, not a trait, however a type parameter constrained to a...

Why does the compiler need that trait hint?

rust,trait

Seems like a bug, I filed #15155. The "problem" is the Send restriction on the http::server::Server. The definition is pub trait Server: Send + Clone { meaning the implementee needs to be both Clone (which is satisfied because you have implemented Clone via #[deriving(Clone)]) and Send. The compiler automatically implements...

Problems returning a value while using a trait and companion object in Scala (Eclipse IDE)

scala,main,value,trait,companion-object

I am not sure why you mention that placing the val x outside the List object prevents you from compiling. The following compiles and produces the expected output = 3 object Work extends App { // These 3 lines define a simplified List type sealed trait List[+A] case object Nil...

Return Trait From Method

rust,trait

Yes. At the moment, you either need to return a &T or a Box<T>, and you're right in this instance, &T is impossible. "Abstract return types" would make returning T possible: https://github.com/rust-lang/rfcs/issues/518...

Ways to write Scala Trait (Mixin)

scala,trait

If I understand your question correctly, you want to define fun1 and fun2 as local function in scope of someFun. Traits in scala unlike interfaces in Java can have implementation. So you can do like this: trait abc { def someFun() { def fun1() { println("Hello") } def fun2() {...

PHP: dealing with traits with methods of same name

php,class,inheritance,scope,trait

You still need to resolve the conflict in favour of one trait. Here you only aliased the name. It's not a renaming, but an alias. Add to the use block: traitA::myfunc insteadof traitB; (or traitB::myfunc insteadof traitA;) and it should work. You now have two aliases as wanted and the...

Why is “abstract override” required not “override” alone in subtrait?

scala,trait

The reason is that the base class method is abstract abstract class IntQueue { def get(): Int def put(x: Int) } If you were to not put abstract on the trait you end up with the explanation you were seeking: trait Doubling extends IntQueue { override def put(x: Int) {...

Why a Trait extending Abstract Class with non-empty constructor compiles?

scala,inheritance,constructor,trait

In your case, you cannot create an anonymous class using Test, because you cannot specify the super constructor arguments, as you've seen. If a trait extends a class, all the classes that mixin the trait has to be either a subclass of that class or a descendant class of that...

How to use trait to add new method to class in Scala?

scala,trait

This is the standard pattern for adding a method to a 3rd party class: class A implicit class ExtendedA(val a: A) extends AnyVal { def methodT: Unit = { println("called A.methodT") } } Then you can do: val a = new A a.methodT ...

Scala: Printing fields and values of given class

scala,reflection,traits,trait

From the Java docs, get requires the object on which the operation is been done. Just change vars(i).get() should be vars(i).get(this) and you are good to go. After making the change, you will get response in scala worksheet as object s { var p: Point = new Point(3, 4) //>...

How to declare a one-method trait

scala,trait

By extending (A => B), you are saying that OneMethod is a function, and can be used directly as such: trait TraitA extends (Int => String) class ClassA extends TraitA { def apply(i: Int) = i.toString } val a = new ClassA (1 to 5).map(a) // IndexedSeq[String] = Vector(1, 2,...

Can a trait guarantee that it is inherited by a companion object at compile- or run-time

scala,trait,companion-object

If the trait must be extended by exactly 1 object, you can check it at compiletime like this: trait Foo { this: Bar.type => ... } object Bar extends Foo If you need several objects to extend it, you could try something based on the Singleton magical type: trait Foo...

Play Framework / Scala: abstract repository and Json de/serialization

json,scala,playframework,implicit,trait

You should be able to just use a context bound. trait Entity { def id: UUID } class Repository[T <: Entity : Writes] { ... } That will ensure that if there exists an implicit Writes[T] in scope, it will be available for your insert and update functions....

What is the reason this Scala trait fails to compile?

scala,trait

You can read test3 = createRocket |> addO2 |> launch as: val intermediateValue = createRocket |> addO2 val test3 = intermediateValue |> launch createRocket |> addO2 translates to addO2(createRocket()), which returns an intermediate value of type Rocket[Fuel, HasO2]. intermediateValue |> launch translates to launch(intermediateValue). launch takes a parameter of type...

UML representation of PHP trait

php,symfony2,uml,behavior,trait

PHP Trait is basically UML Abstract Class or UML Class Template connected to the used-in class with the UML Generalization Relationship utilizing the multiple inheritance notation See also: Figure "UML Diagram with a Trait" in article Brendan Bates: Traits: The Right Way Programmers: Is there a representation for mixins or...

How to override methods in a Scala trait?

scala,dependency-injection,trait

The problem is that you're technically not implementing the two methods in the MatchingEngine trait. The trait specifies: def crosses(incoming: Order, top: Order): Boolean def formPrice(incoming: Order, top: Order): Double But you implemented: def crosses(incoming: LimitOrder, top: LimitOrder): Boolean def formPrice(incoming: LimitOrder, top: LimitOrder): Double You could solve it with...

AbstractMethodError when mixing in trait nested in object - only when compiled and imported

scala,inheritance,trait

It's clearly a bug. If you: java.lang.AbstractMethodError: $line13.$read$$iw$$iw$$iw$$iw$$iw$$iw$$anon$1.foo()I ... 33 elided scala> :javap -p $line13.$read$$iw$$iw$$iw$$iw$$iw$$iw$$anon$1 Compiled from "<console>" public final class $line13.$read$$iw$$iw$$iw$$iw$$iw$$iw$$anon$1 implements p.Base,p.Impls$ConcreteImpl { public java.lang.Object foo(); public $line13.$read$$iw$$iw$$iw$$iw$$iw$$iw$$anon$1(); } It doesn't have a foo with result type Int. Offhand, I can't imagine the difference in the REPL, but...

How to unit test PHP traits

php,unit-testing,phpunit,trait

You can test a Trait using a similar to testing an Abstract Class' concrete methods. PHPUnit has a method getMockForTrait which will return an object that uses the trait. Then you can test the traits functions. Here is the example from the documentation: <?php trait AbstractTrait { public function concreteMethod()...

Provide inheritance-like behavior for traits in Rust

rust,trait

Traits in Rust are not regular types. They either can be used as generic bounds or as trait objects, which are regular types but which also require some kind of indirection to work with them (a reference or a Box). You, on the other hand, are trying to implement Parser...

Scala: class type required but T found

scala,types,scala-2.10,trait

Here's an intermediary solution, though it leaves out the converter registration (which I may leave permanently for this use case, not sure yet). /** * trait for adding write methods to classes */ trait RiakWriteable[T] { /** * bucket name of data in Riak holding class data */ def bucketName:...

Appending a char to a string in rust

rust,trait

I presume you are using 0.10 documentation and a master build. In preparation for the brave new world of Dynamically Sized Types, where ~str (a.k.a. Box<str>) does not contain a capacity but only a length and thus cannot efficiently be pushed to as it would require reallocating every single time,...

Scala traits hierarchy doesn't compile

scala,inheritance,trait

There were a couple of issues, primarily stemming from using val in superclasses, which locks it down to a value, rather than something that can be overridden and accessed via super. There were also some problems with not specifying override: trait Animal { // in order for super to be...

Scala trait, superclass and early definition syntax

scala,inheritance,buffer,inputstream,trait

Edit: The syntax for implementing a class with pre-initialized fields is class ImplementingClass extends {val field1 = ???; val field2 = ???} with AbstractSuperclass with Trait1 with Trait2 Note that, despite the keyword with, the (abstract) superclass needs to be at the first position and you cannot extend multiple classes....

Traits not implemented in finagle service

scala,typeclass,trait,finagle

AdditionServer is the object which is extending Transformer. In your code, this object is not defining neither extractPayload nor responsePayload thus the compilation error you get. You should move your methods definitions from the trait companion object to AdditionServer object AdditionServer extends App with Transformer[HttpRequest,Add,Result,HttpResponse] { import Transformer._ def extractPayload(r:HttpRequest):Add...

Symfony : is there a best practice about the directories' name including traits and interfaces?

php,symfony2,interface,trait

Regarding naming convention, see coding standards Regarding directory structure, I don't specifically put them in a trait directory. It depends on how you want to organize your code. Generally, most people will put the trait inside a package folder for the behaviour it represents, i.e., Mysql\ConnectionTrait...

Why does scalac infer `Foo with Bar` not just `Foo` for match/case return type?

scala,trait

Scala infers the most specific type it can. Each of the four instances is both a Model and a GeoEntity, so that's the inferred type: Model with GeoEntity. If you want the function to return the less specific type of Model (all Model with GeoEntitys are Models, but not all...

Scala: Mis-using traits, gives runtime error

scala,trait

When I paste your code into a Scala 2.11.6 REPL I don't get any errors at first. Trying to access myProperty will result in a NullPointerException scala> Top.myProperty java.lang.NullPointerException at MiddleTrait$class.$init$(<console>:12) ... 35 elided The NullPointerException is thrown because MiddleTrait gets initialized before Top at which point property is still...