1

All!

I want to use type parameter for create subclass, but scala give the "error: class type required but T found". For example:

abstract class Base {def name:String}
class Derived extends Base {def name:String = "Derived"}
class Main[T <: Base] 
{
    class SubBase extends T {}; // <--- error: class type required but T found
    val x:SubBase; 
    println(x.name) 
}
val m:Main[Derived]

I want this way instead normal inheritance because in real code I have lazy variables, declared in Base and defined in Derived, and these variables should perform a computation in Main class

How I can do it? Thanks in advance

1
  • This is not possible, partly because of type erasure otherwise because of no runtime code generation. In this case composition is preferred over inheritance in my opinion. Commented Feb 11, 2015 at 19:41

1 Answer 1

1

You can use a self-type to achieve a similar effect:

abstract class Base {def name:String}
class Derived extends Base {def name:String = "Derived"}
class Main[T <: Base] 
{
    trait SubBase { this: T => };
    val x:SubBase; 
    println(x.name)  // <--- error: value name is not a member of x
}
val m:Main[Derived]

However, this will only give you access to the members of T inside the class. Therefore, you can additionally have SubBase extend Base:

abstract class Base {def name:String}
class Derived extends Base {def name:String = "Derived"}
class Main[T <: Base] 
{
    trait SubBase extends Base { this: T => }
    val x:SubBase; 
    println(x.name)
}
val m:Main[Derived]

This will compile, but is not useful, since the fact that SubBase is also a T remains private to SubBase.

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

1 Comment

Private T is never mind for my case. But I can not make mixin with this SubBase and other class for make "diamond" incheritance structure. May be it is not possible. I'll try to read something more about self-types in scala, thank you for this way.

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.