在实例化对象之前可以引用对象的成员吗?
这就是我想要做的(警告:前面的 Scala 极其损坏):
def assignToFour[X](x : X, y : Something[X]) = x.y = 4
class M {
var m = 0;
}
val em = new M
assignToFour(em, M.m)
em.m == 4
显然,这根本行不通,但我正在寻找一种模式,允许我引用以下成员:抽象中的实例,然后在稍后的某个时刻,访问实际实例上的该成员。
如果这是 Java,我会使用反射,但反射很糟糕,我希望 Scala 能有一个更好的选择,因为它比 Java 糟糕得多。
Here's what I want to do (warning: extremely broken Scala ahead):
def assignToFour[X](x : X, y : Something[X]) = x.y = 4
class M {
var m = 0;
}
val em = new M
assignToFour(em, M.m)
em.m == 4
Obviously, that won't work at all, but I'm looking for a pattern that will allow me to refer to an member of an instance in the abstract and then at some later point, access that member on an actual instance.
If this were Java, I would use reflection, but reflection sucks and I am hoping Scala, which sucks so much less than Java, would have a better alternative.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
所以:
var m
,getter 方法将被命名为m
,setter 方法将被命名为m_=
从这里开始:
xm 当前为 0,让我们更改它...
下面的方法采用 Function 作为参数,并使用值
4
调用该函数:并使用它:
其中
x.m_=
是4
的 setter 方法。实例x
上的 code>m 属性xm
现在等于 4。So:
var m
the getter will be namedm
and the setter method will be namedm_=
Starting here:
x.m is currently 0, let's change that...
Here's a method that takes a Function as its argument, and calls that function with the value
4
:And using it:
Where
x.m_=
is the setter method for them
property on the instancex
x.m
is now equal to four.虽然结构类型是一种替代方案,但它们在内部使用反射。
您实际上想要做的是调用某个属性的 setter,以便您可以将其概括为函数调用:
此方法采用两个参数:
X
的某个实例和一个函数f
> 将您的X
转换为从Int
到某种类型Y
的函数(在您的情况下,这将是Unit
)。使用 或 在更短但可读性较差的变体中调用它:
现在,您可以使用生成的 setter
m_=
While structural types are an alternative they use reflection internally.
What you actually want to do is invoke the setter of some property so you can generalize it to a function call:
This method takes two arguments: some instance of
X
and one functionf
that turns yourX
into a function fromInt
to some typeY
(this will beUnit
in your case).Now you can invoke it using
or in a shorter but less readable variant using the generated setter
m_=
:您可以使用
结构类型
,这样您就不会依赖于特定类型(尽管失去了一些灵活性,无法传递要更新的属性名称):You can use
structural types
, so you won't depend on a specific type (though lose some flexibility no being able to pass the name of the property to update):