Scala: Why scala allows you to implement function literals using Map / List / etc

I defined the scala trait as follows:

trait Example {
  def func: Int => Int
}

And the compiler allows me to implement it:

class SomeClass extends Example {
   def func = Map(1->2, 3->4)
}

I can replace Mapwith List, it will work anyway. My question is why? I did not declare funcas a literal of the function, which should be implemented as a function?

At a deeper level, how does the scala compiler verify function signatures?

Thank!

+4
source share
1 answer

Int => Intdroppers up Function1[Int, Int]. Both Map[K, V]and List[A]are expanding indication Function1[A, B]as part of the hierarchy of their collection and, therefore, the compiler resolves these types of as a concrete realization.

For example, Map:

trait MapLike[K, +V, +This <: MapLike[K, V, This] with Map[K, V]] extends PartialFunction[K, V]

Where PartialFunction[K, V]goes onFunction1[K, V]

+4
source

Source: https://habr.com/ru/post/1692856/


All Articles