Home > Software engineering >  Scala: Can I write my function like a method of type?
Scala: Can I write my function like a method of type?

Time:05-20

Is it possible to write postfix function that I can use like that:

//...

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
}

//...

I want to call my function like if it's a method of type String. It there such possibility? If there is, what syntax I have to use?

CodePudding user response:

It sounds like what you're asking is whether you can add a method to the String type. Yes, you can do that with an implicit class. See, for example, https://www.baeldung.com/scala/implicit-classes.

CodePudding user response:

In Scala 2 and without Scalaz or other non-core functional lib:

(myFunction compose otherMyFunction) (myStr)

Scala 2.13 you can use the pipe chaining operator

  • Related