Add ability to declare pattern matched values as implicit

It would be nice if we could mark the values that have been matched in a pattern as implicit. Not having this ability means that we need to reassign values that have just been pattern matched to a new implicit val to make them available in the implicit scope of the case.

Here’s a simple example. Say I want the boolean to be available in the implicit scope of the match, I have no choice but to do this:

val seq = (123,"Words",true)

seq match {
    case (a: Int,b: String,c: Boolean) => {
        implicit val c2 = c
        implicitly[Boolean]
        println("Works")
    }
}

This seems repetitive and unnecessary. It would be nice if we could do something like this

val seq = (123,"Words",true)

seq match {
    case (a: Int,b: String,implicit c: Boolean) => {
        implicitly[Boolean]
        println("Would be nice if this worked")
    }
}

Here’s a more involved and more realistic scenario on scastie that actually gave me the idea

And here’s the original issue from github

It seems we can already do this on parameters to lambda functions, so why not add it to pattern matching as well?

5 Likes

A related thing that would be nice is if you could import non-implicit definitions as implicit.

For example, if you wanted Numeric.BigDecimalAsIfIntegral in scope as an implicit, you would normally need to do:

def foo[A: Integral](a: A) = ???

import scala.math.Numeric.BigDecimalAsIfIntegral

implicit val integral = BigDecimalAsIfIntegral
foo(BigDecimal(0.0))

but instead you could do:

def foo[A: Integral](a: A) = ???

import implicit scala.math.Numeric.BigDecimalAsIfIntegral

foo(BigDecimal(0.0))

(Disallowing importing wildcards as implicits might also be good idea, for sanity reasons.)

3 Likes

Related to SI-2823, implicit is not allowed in for comphrehensions. A PR allowing that was closed because it wasn’t general enough.

pretty huge caveat: see meeting notes (scala/scala-lang#358). @odersky seemed uninterested in having this go forward unless it’s for patterns in general, not just for for comprehensions in particular. that’s substantially more ambitious.

1 Like