Search code examples
scalainheritancetype-parameter

use type parameter for create subclass in scala language


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


Solution

  • 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.