Type inference with existential type

后端 未结 1 1343
别那么骄傲
别那么骄傲 2020-12-19 21:11

I have a generic trait SomeTrait defined as so:

trait SomeTrait[T] {
  def foo(t: T): String
}

And methods bar an

相关标签:
1条回答
  • 2020-12-19 21:19

    The correct way to do this is to use a type variable to give a name to T:

    qux map { case x: SomeTrait[t] => x.foo(bar(x)) }
    

    This way the compiler knows bar(x): t and so it's an acceptable argument to x.foo.

    Or, alternately, you can combine foo and bar into one method (remember that methods can be local, so you can just define it where you need it):

    def fooOfBar[T](x: SomeTrait[T]) = x.foo(bar(x))
    qux map { fooOfBar(_) }
    
    0 讨论(0)
提交回复
热议问题