Scala version - 2.13
Code
def foo[A <: String]: Function1[String, Int] = new Function1[String, Int] {
override def apply(a: A): Int = 1
}
This give a compilation error
object creation impossible. Missing implementation for:
def apply(v1: String): Int // inherited from trait Function1scalac
A is a subtype of String. Why is this not allowed?
The first type argument that you provided to Function1
is String
but you defined the parameter a
in apply
to be of type A
.
The error that I get is:
error: object creation impossible. Missing implementation for:
def apply(v1: String): Int // inherited from trait Function1
override def apply(a: A): Int = 1
^
On line 2: error: method apply overrides nothing.
Note: the super classes of <$anon: String => Int> contain the following, non final members named apply:
def apply(v1: String): Int
You need to specify A
as the type argument to Function1
like so:
def foo[A <: String]: Function1[A, Int] = new Function1[A, Int] {
override def apply(a: A): Int = 1
}
1 Like