I am trying to figure out why the classes below compile without error in Scala.
I would expect the createTestClass
method in the DoTest
class to fail with a typing error because it tries to supply the implicit parameter which has type TypeClass[A]
, but instead of such an instance, it provides a lambda with type A => String
.
Is there some implicit conversion at work here? How would I go about figuring out what's going on?
object Test {
trait TypeClass[A] {
def asString(a: A): String
}
object TypeClass {
def apply[A: TypeClass]: TypeClass[A] = implicitly[TypeClass[A]]
}
case class TestClass[A: TypeClass](foo: Option[A] = None)
object TestClass {
def apply[A: TypeClass]: TestClass[A] = TestClass[A]()
}
}
object DoTest {
import Test.TestClass
def createTestClass[A]: TestClass[A] =
TestClass.apply[A]((_: A) => "test")
}
Scala 2.12 introduced a new feature: lambda syntax for SAM (Single Abstract Method) types. That's simply what you're seeing here.