jcazevedo
jcazevedo

Reputation: 217

How can I bound a type parameter for Tuples without relying on Product?

I'm trying to declare a function with a type parameter that I want to bound so that only instances of TupleN are accepted. However, I don't want to bound on Product as instances of case classes, for example, should not be accepted. For instance, if the function is named foo:

case class Foo(a: Int, b: String)
foo(Foo(1, "str")) // should not compile
foo((1, "str"))    // should compile

I can achieve this by enumerating all TupleN instances for a custom type class and then using a context bound on the type parameter, but I'd prefer to avoid it.

Is it possible to do that in a simpler way?

Upvotes: 2

Views: 120

Answers (2)

jcazevedo
jcazevedo

Reputation: 217

If you're OK with depending on shapeless, you can rely on the IsTuple type class to provide evidence that a given type is a Scala tuple:

import shapeless._

def foo[A: IsTuple](v: A) = ???
foo((1, "str")) // compiles
foo(Foo(1, "str")) // does not compile due to lack of evidence

Upvotes: 1

Alexey Romanov
Alexey Romanov

Reputation: 170919

No, that's the right way to do it. You could do it using a macro, but it wouldn't be simpler.

Upvotes: 1

Related Questions