Understanding `f: Int => _`

Given:

scala> def foo(x: Int)(f: Int => _) = ???
foo: (x: Int)(f: Function1[Int, _])Nothing

What is the point Function1[Int, _]?

Is _existential? How can I call him?

+4
source share
1 answer

_is an existential type. In particular, an unrelated pattern. Without any restrictions, the compiler will just do it like Anythat, but you can pass any function Function1[Int, A], since the only restriction is A <: Any, and is Function1covariant over A.

scala> def foo(x: Int)(f: Int => _) = f(x)
foo: (x: Int)(f: Function1[Int, _])Any

scala> def f(i: Int): Int = i
f: (i: Int)Int

scala> foo(1)(f)
res2: Any = 1

This works, but the result fis Any, which makes it not very useful.

You can add an upper border to it, and this border will be displayed:

scala> def foo(x: Int)(f: Int => _ <: Int) = f(x)
foo: (x: Int)(f: Function1[Int, _ <: Int])Int

scala> foo(1)(f)
res6: Int = 1

, , , ? .. List[Function1[Int, _]]. , .

+4

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


All Articles