Reputation: 624
Instead of describing the problem in words, let me just show you a Scala Interpreter session that shows what I want to do.
scala> class A extends Parent{
| def name = "Alex"
| }
defined class A
scala> class B extends Parent{
| def name = "Bernardo"
| }
defined class B
scala> def addFamilyName[T <: Parent](fn:String, c:T{def name():String}) = c.name + " " + fn
addFamilyName: [T <: Parent](fn: String, c: T{def name(): String})java.lang.String
scala> addFamilyName( "Martins", new A())
<console>:11: error: type mismatch;
found : A
required: ?{def name(): String}
addFamilyName( "Martins", new A())
^
So basically I want to define a type in a parameter that is both a subclass of a certain type and also contains a method with the signature def name():String
.
NOTE: I'm trying to do it this way because my class hierarchy is already way to complicated. Given this, I prefer to not add a ParentWithName
abstract class
or trait
if it can be avoided.
Upvotes: 2
Views: 262
Reputation: 39366
Believe it or not, the issue is in the parentheses in the method signature. This works:
def addFamilyName[T <: Parent](fn:String, c:T{def name:String}) =
c.name + " " + fn
Though I should add you don't actually need a type parameter. This is just as good:
def addFamilyName(fn:String, c:Parent{def name:String}) =
c.name + " " + fn
Upvotes: 6