使用函数作为类方法

时间:2011-11-08 06:27:12

标签: class function scala implicit-conversion

我试图找出如何使用函数作为类的成员,但无法弄清楚正确的语法。我收到编译错误:

test.scala:11: error: missing arguments for method extra in class RichString;
follow this method with `_' if you want to treat it as a partially applied function
println("This is".extra);

如何将extra保留为在类RichString之外定义的函数并使用它来扩展String类?

感谢。

test.scala:

 
class RichString(a: String) {
  def extra(a: String):String
}

def extra(a: String): String = {
  return a+" Extra!";
}

implicit def string2Rich(s: String) = new RichString(s);

println("This is".extra);

1 个答案:

答案 0 :(得分:1)

这是你想要的吗?

scala> class RichString(a: String) {
     |   def extra = a + "extra"
     | }
defined class RichString

scala> implicit def enrichString(s: String) = new RichString(s)
enrichString: (s: String)RichString

scala> println("this is".extra)
this isextra