Alexander Lopatin
Alexander Lopatin

Reputation: 582

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

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?

Upvotes: 0

Views: 65

Answers (2)

Emiliano Martinez
Emiliano Martinez

Reputation: 4133

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

Upvotes: 1

ndc85430
ndc85430

Reputation: 1743

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.

Upvotes: 2

Related Questions