miguel0afd
miguel0afd

Reputation: 315

Scala type parameter with multiple types as result of function

I'm trying to implement a project where there are traits:

`trait Checkable`

`trait Closeable`

and a class:

`case class DBConnection (url: String) extends Checkable with Closeable`

and a function

`def generateConnection[T <: Checkable with Closeable](url: String): T = DBConnection(url)`

On compiling the above code, it generates error:

`Expression of type DBConnection doesn't conform to expected type T_`

What can I do to solve this issue?

I can use the expression:

`DBConnection(url).asInstanceOf[T]`

But I don't think it's the best practice

Upvotes: 2

Views: 223

Answers (1)

slouc
slouc

Reputation: 9698

Your method says it would return T, where T is a subtype of Checkable with Closeable. But then it returns a DBConnection. What if the user invoked this method parameterized with MyCustomDBConnection? She would expect that same type as a result, and instead she would receive your DBConnection.

You are making a promise you can't keep. It's better to revoke the opportunity to set the type T, and only promise that you'll return a Checkable with Closeable. Then everything should compile fine.

def generateConnection(url: String): Checkable with Closeable = DBConnection(url)

If you still want to parameterize your method with T, then you will have to make a typeclass which would provide different implementations for different variants of T. You can't just return a DBConnection every time, because what's the point of T then.

Upvotes: 6

Related Questions