0
scala> trait BaseTrait[T] { def foo(e: T): String}
defined trait BaseTrait

scala> class C1 extends BaseTrait[String] {def foo(e: String) = "C1"}
defined class C1

scala> class C2 extends BaseTrait[Int] {def foo(e: Int) = e.toString}
defined class C2

scala> def general(e :BaseTrait) = {println(e.foo())}
<console>:43: error: trait BaseTrait takes type parameters
`enter code here`def general(e :BaseTrait) = {println(e.foo())}

That defeats polymorphic behavior...how do I define generic functions that consume BaseTrait?

2
  • 1
    def general(e :BaseTrait[_]) but this is still not going to work. e.foo takes parameters. Check parametric polymorphism, it seems you want ad hoc polymorphism. Commented Apr 28, 2017 at 20:38
  • 1
    @user7938511 You conveniently didn't specify where you were going to get a valid argument to pass to foo without parametrizing. Commented Apr 28, 2017 at 20:42

1 Answer 1

1

One valid definition of general would be

def general[A](e: BaseTrait[A], a: A) = println(e.foo(a))
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.