简体   繁体   中英

Scala mixin to class instance

Is it possible in Scala to make some mixin to class instance?

Eg: I have some MyClass instance var x = new MyClass and I want to extend it on some method or trait without copying it.

[Edit:]
I'm looking the way to extend x after it has been instantiated. So, for example in a function method, which gets x as a parameter.

[What is behind]
I've just wonder if there is some magic with implicit objects and Manifest to achieve the typeclass pattern without explicit call implicit object (like in Haskell). But only for single object.

I know if is artificial, but I've just wonder if it's possible because of lot of magic with mixing Scalas features.

you mean like:

val x = new MyClass with MyTrait

Yes you can. Just overriding methods obviously can be:

val x = new MyClass { 
  override def myMethod = { my implementation }
} 

Just came across this problem as I was wondering the same thing...

case class Person(name: String)
val dave = Person("Dave")
val joe  = Person("Joe")

trait Dog { val dogName: String }
val spot = new Dog { val dogName = "Spot" }

implicit def daveHasDog(p: dave.type) = spot

dave.dogName //"Spot"
joe.dogName  //error: value dogName is not a member of Person

So now the dave instance (rather than all instances of class Person) behaves like a Person with Dog , at long as the implicit is in scope.

This will work in most cases, except where your trait has self-types.

It is not possible. You may look at using the Dynamic trait or Kevin Wright's auto-proxy plugin , but, either way, you'll create a new object that also answers to the original one's method through proxying.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM