Home > other >  Why does implicit conversion not work with PartialFunction
Why does implicit conversion not work with PartialFunction

Time:10-05

Say I define the following:

type Func1 = PartialFunction[Int, String]
case class A(f: Int => String)
implicit def toA(func: Func1): A = A(func(_))

Then I might want to use the implicit conversion thus:

val a: A = {
    case i: Int => i.toString
}

But this does now compile. However explicit use of the function is fine:

val a: A = toA({
    case i: Int => i.toString
})

Why is this?

CodePudding user response:

val f = {
  case i: Int => i.toString
}

doesn't compile either:

missing parameter type for expanded function

The argument types of an anonymous function must be fully known. (SLS 8.5)

Expected type was: ?

val f = {

According to Scaladocs, working code is

val f: PartialFunction[Int, String] = {
  case i: Int => i.toString
}

If you want implicit conversion try

val a: A = {
  case i: Int => i.toString
} : PartialFunction[Int, String]
  • Related