简体   繁体   中英

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

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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM