2

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

1 Answer 1

6

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.