scala 自动转换函数/方法?

发布于 2024-11-25 11:31:35 字数 235 浏览 3 评论 0原文

我有一堂有很多方法的课。

class C{
def f1(x:String,....):...=..
def f2(..)...
.
.
.

}

我现在希望类中定义的每个方法都自动用我选择的特征进行装饰。 类似于创建一个棘手的隐式矿石,它可以装饰每个方法,并且可能返回带有装饰方法的类的实例。也许是包装或修改了什么的。我无法描述更多的方式,因为我不认识路。 你知道有办法做到这一点吗?

I have got a class with many methods.

class C{
def f1(x:String,....):...=..
def f2(..)...
.
.
.

}

I want now that every method defined in my class is decorated with a trait of my choice automatically.
Something like to create a tricky implicit ore something what decorates every method and perhaps returns an instance of the class with decorated methods. Perhaps wrapped or modified or something. I can not describe more of the way because i dont know the way.
Do you know a way to do that?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

夜唯美灬不弃 2024-12-02 11:31:35

方法不是函数,尽管当您将它们传递给需要函数的方法时,它们会自动被提升。另请参阅 http://jim-mcbeath.blogspot.com /2009/05/scala-functions-vs-methods.html

如果你真的有函数:

class C {
  val f1 = (x: String, ...) =>
  val f2 = (...) =>
  ...
}

并且你希望它们混合在一个特征中,比如:

class C {
  val f1 = new FunctionN[String, ...] with Gaga {
    def apply(s: String, ...) = ...
  }
  val f2 = new FunctionN[...] with Gaga { ... }
  ...
}

我能想到的唯一方法是将你的类提交给 Scala-Refactoring 之类的东西: http://scala-refactoring.org/

Methods are not functions, although they will automatically be lifted when you pass them to a method that requires a function. See also http://jim-mcbeath.blogspot.com/2009/05/scala-functions-vs-methods.html

If you really have functions:

class C {
  val f1 = (x: String, ...) =>
  val f2 = (...) =>
  ...
}

and you want them to mix in a trait, like:

class C {
  val f1 = new FunctionN[String, ...] with Gaga {
    def apply(s: String, ...) = ...
  }
  val f2 = new FunctionN[...] with Gaga { ... }
  ...
}

the only way I can think of is submit your class to something like Scala-Refactoring: http://scala-refactoring.org/

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文