Type inferred to Nothing in Scala

前端 未结 2 928
眼角桃花
眼角桃花 2020-12-09 11:58

When I try to compile the small example:

trait Foo[A,B] {
  type F[_,_]
  def foo(): F[A,B]
}

class Bar[A,B] extends Foo[A,B] {
  type F[D,E] = Bar[D,E]
  d         


        
相关标签:
2条回答
  • 2020-12-09 12:20

    Would it work to use type members instead of parameters?

    trait Foo {
      type A
      type B
      type F
      def foo(): F
    }
    
    class Bar extends Foo {
      type F = Bar
      def foo() = this
    }
    
    object Helper {
      def callFoo[FF <: Foo]( f: FF ): FF#F =
        f.foo()
    }
    
    object Run extends App {
      val x = new Bar{type A=Int; type B=Double}
      val y = Helper.callFoo(x)
      println( y.getClass )
    }
    

    When using type members, it's useful to know that they can be surfaced as type parameters using refinement, as in Miles Sabin's answer to: Why is this cyclic reference with a type projection illegal?

    See also this recent question, which seems similar to yours: Scala fails to infer the right type arguments

    0 讨论(0)
  • 2020-12-09 12:27

    You'll have to change the signature of callFoo to this:

    def callFoo[A, B, FF[A, B] <: Foo[A, B]](f: FF[A, B]): FF[A, B]#F[A, B] =
    

    You have to tell the compiler that FF is actually a parametrized type.

    0 讨论(0)
提交回复
热议问题