Yann Moisan
Yann Moisan

Reputation: 8281

How to specify only few type of a polymorphic method

Given the following code

def doAction[A:Reads, B:Writes](bizMethod: A => B) = …
def f = doAction(g)

In some cases, the compiler can't infer the type. For example, g input parameters is not convertible to Reads, but we will call the method with an instance of a subclass that is Readable. So I want to fix the first type and let the compiler determines the second one, as def f = doAction[XXX, _](g)

[update] For a better comprehension of the issue, I've add code to illustrate the question :

trait Sth[A]
implicit val StringSth = new Sth[String]{}
def doAction[A:Sth,B:Sth](f: A => B) = f

def g(i: String) = "Str" + i
val gg = doAction(g)

def h(a: Any) = a.toString
def hh = doAction(h) // doesn't compile, it's normal
def hh[String] = doAction[String, _](h) //doesn't compile

I want to call hh with a String

Upvotes: 1

Views: 51

Answers (1)

Kevin Wright
Kevin Wright

Reputation: 49695

I may have misunderstood the question, but it sounds as though you're after type lambdas.

You'll find lots of matches if you search Google for the term, but this is probably the cleanest explanation.

UPDATE

In this case, the easiest way is just to use type ascription and inform the compiler that you'll be using h as though it were an instance of String => String (which is valid, because contravariance means that String=>String is a superclass of Any=>String).

Then you can let the rest of the implicit machinery work without further tweaks:

val h = (a: Any) => a.toString
val hh = doAction(h: String => String)

As an added benefit, the intent of your code is far clearer if you do it this way.

Upvotes: 1

Related Questions