3

I have a number of traits that I am implementing which have methods of a signature something like

trait MyCache {

     def getMyThing(key: String): Future[Option[MyThing]] 

     def setMyThing(data: MyThing, key: String): Future[Boolean] 

}

I also have a generator function for these getters and setters that generates functions that (almost) map to these method traits. The simplified getters and setters generator produces functions (not methods) with the signature

val getMyThingGenerated: String => Future[Option[MyThing]]

val setMyThingGenerated: (MyThing, String) => Future[Boolean]

I would like to map in succinct manner between these generated functions and class methods but I am not sure how.

I could write something like

class CacheImplementation extends MyCache {

    def getMyThing(key: String): Future[Option[MyThing]] = 
        getMyThingGenerated(key)

    def setMyThing(data: MyThing, key: String): Future[Boolean] =
        setMyThingGenerated(data, key)
}

but this seems somewhat overkill when I know that the method and function have similar signatures. I was hopefully that this could be done with partial function application but I can't seem to make it work.

1 Answer 1

2

If what you want is something similar to

def getMyThing(key: String): Future[Option[MyThing]] = getMyThingGenerated

then I don't think it's possible with Scala (at least without macros). The important thing to realize is that even though defining a method contains a = symbol, it is not an assignment. While this works

val getMyThing: String => Future[Option[MyThing]] = getMyThingGenerated

a similar syntax for a def is invalid. The Scala specification states that a function body is "an expression which defines the function's result". To get the expression of the correct type, you need to apply your function, which is what you show in your examples:

def setMyThing(data: MyThing, key: String): Future[Boolean] = setMyThingGenerated(data, key))

I'm not aware of any way how to add a method to a class without the def definition which has these limitations.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.