3

I have a generic trait SomeTrait defined as so:

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

And methods bar and qux as so:

def bar[T](t: SomeTrait[T]): T
def qux: List[SomeTrait[_]]

I do not have control over the above. I am trying to operate on the list returned by qux, like so

qux map { x => x.foo(bar(x))}

However, the compiler complains that the types don't match up. As far as I know this should be fine.

I have tried adding a generic method (signature [T](SomeTrait[T])String), and calling that to do the work, but the compiler still complains. I can cast my way around it like this:

qux map { x =>
  val casted = x.asInstanceOf[SomeTrait[T forSome { type T }]] // !!!
  casted.foo(bar(casted))
}

But this is even more perplexing, as x already has the type SomeTrait[_] and SomeTrait[T forSome { type T }] means the same thing. The only difference that I'm aware of is that the former is a shorthand for the latter that makes the compiler create its own synthetic names. I'm hoping there's a better way to do this. I have seen this question however I don't think it applies.

Community
  • 1
  • 1
HTNW
  • 27,182
  • 1
  • 32
  • 60

1 Answers1

4

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(_) }
Alexey Romanov
  • 167,066
  • 35
  • 309
  • 487
  • What is `t` and how is it an acceptable argument to `x.foo`? Can you elaborate? – Yuval Itzchakov Jul 28 '16 at 07:04
  • @YuvalItzchakov It's a type variable pattern, see http://scala-lang.org/files/archive/spec/2.11/08-pattern-matching.html#type-patterns. It just lets you give a name to the existential parameter in a pattern match, as the first sentence says. And because `SomeTrait[T].foo` need a `T` parameter, then of course `SomeTrait[Int].foo` needs `Int` and `SomeTrait[t].foo` needs `t`. – Alexey Romanov Jul 28 '16 at 07:16
  • The latter is actually *really* strange, as omitting the braces (`qux map fooOfBar`) causes the compiler to complain about types again. But it works fine the way it's given. Why does that happen? – HTNW Jul 28 '16 at 10:20
  • 1
    If you write `qux map fooOfBar`, this is really `qux map fooOfBar[T]` where `T` has to be inferred by the compiler. And there is no value of `T` which would work (if it did, it would have to be one `T` for all elements of `qux`). `qux map { fooOfBar(_) }` is short for `qux map { x => fooOfBar[T](x) }` and now `T` can depend on `x`. – Alexey Romanov Jul 28 '16 at 11:41