简体   繁体   English

Scala mixin到类实例

[英]Scala mixin to class instance

Is it possible in Scala to make some mixin to class instance? 在Scala中是否可以将一些mixin转换为类实例?

Eg: I have some MyClass instance var x = new MyClass and I want to extend it on some method or trait without copying it. 例如:我有一些MyClass实例var x = new MyClass ,我想在某些方法或特征上扩展它而不复制它。

[Edit:] [编辑:]
I'm looking the way to extend x after it has been instantiated. 我正在寻找在实例化后扩展x的方法。 So, for example in a function method, which gets x as a parameter. 因此,例如在函数方法中,它将x作为参数。

[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). 我只是想知道是否有一些神奇的隐式对象和Manifest来实现类型类模式而没有显式调用隐式对象(比如在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. 我知道如果是人为的,但我只是想知道它是否可能因为混合了Scalas功能的大量魔力。

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. 所以现在dave 实例 (而不是类Person的所有实例)的行为就像一个Person with Dog ,只要隐含在范围内。

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. 您可以查看使用Dynamic trait或Kevin Wright的自动代理插件 ,但无论如何,您将创建一个对象,该对象也通过代理来回答原始对象的方法。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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