Scala:我可以像类型方法一样编写我的函数吗?

Scala: Can I write my function like a method of type?

是否可以编写我可以使用的后缀函数:

//...

val myStr: String = "some string"

val myNewStr = myStr myFunction otherMyFunction // Instead of: otherMyFunction(myFunction(myStr))

def myFunction(String: str): String {
//do something
}

def otherMyFunction(String: str): String {
//do something
}

//...

我想像调用 String 类型的方法一样调用我的函数。有这种可能吗?如果有,我必须使用什么语法?

听起来你问的是是否可以向String 类型添加方法。是的,您可以使用隐式 class 来做到这一点。例如,参见 https://www.baeldung.com/scala/implicit-classes.

在 Scala 2 中且没有 Scalaz 或其他 non-core 功能库:

(myFunction compose otherMyFunction) (myStr)

Scala 2.13 你可以使用管道 chaining operator