It is not possible to resolve type-dependent class type proof without access to value type

I was stuck for an hour to discover this fact:

class Foo {
  trait TypeClass[X]
  object TypeClass {
    implicit val gimme = new TypeClass[Int]{}
  }

  def foo[X : TypeClass](p: X): Unit = println("yeah " + p)
}

    // compiles
val foo = new Foo()
foo.foo(4)

    //does not compile
new Foo().foo(4)

    could not find implicit value for evidence parameter of type _1.TypeClass[Int]
    [error]   new Foo().foo(4)
    [error]    

I can’t understand why this is so. The only thing I can think of is that scalac does not find implicits in a type that does not have a value type available on any prefix. It cannot be referenced. Obviously, Scalac needs to access this Foo.this.footo resolve the implications in it, which in this case it cannot be.

, , , . . , scalac API-, . , Foo[T], api , , ...

+4
1

, , , , :

scala> var foo = new Foo()
foo: Foo = Foo@4bc814ba

scala> foo.foo(4)
<console>:17: error: could not find implicit value for evidence parameter of type    _37.TypeClass[Int]
          foo.foo(4)
                 ^

scala> def foo = new Foo()
foo: Foo

scala> foo.foo(4)
<console>:17: error: could not find implicit value for evidence parameter of type _39.TypeClass[Int]
          foo.foo(4)
                 ^

_37 , . , , scala , val. , :

scala> class C {type K = Int}
defined class C

scala> var z = new C
z: C = C@4d151931

scala> def aaa(a: z.K) = a
<console>:16: error: stable identifier required, but z found.
   def aaa(a: z.K) = a
              ^

scala> def z = new C
z: C

scala> def aaa(a: z.K) = a
<console>:16: error: stable identifier required, but z found.
   def aaa(a: z.K) = a
              ^

new Foo def newFoo = new Foo, .

+4

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


All Articles