我试图找出如何使用函数作为类的成员,但无法弄清楚正确的语法。我收到编译错误:
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);
答案 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