object Test1 extends App {
object specificTypes extends Enumeration {
type specificTypes = Value
val Red = Value
val Green = Value
val Blue = Value
}
abstract class outer {
type T <: Test1.specificTypes.Value
def pr(w: T)
}
class red extends outer {
type T = Test1.specificTypes.Red // Getting Error Here, type Red is not a member of object Test1.specificTypes
def pr(w: T) = println("hello red")
}
val r = new red
r.pr(Test1.specificTypes.Red)
}
类型Red不是对象Test1.specificTypes
的成员,如何解决它,我要去哪里错误
答案 0 :(得分:1)
我认为如果你想保持类似的结构,最好将类型T存储在伴侣对象中。否则你可以使用和类型并执行类似的操作
sealed trait Colour
trait Red extends Colour
trait Green extends Colour
class RedClass extends Red
class GreenClass extends Green
def matchMethod(check:Colour) = {
check match {
case Red => println("hello this is red")
case Green => println("hello this is green")
}
}
通过这种方式,您可以完全匹配且安全地匹配,而无需奇怪的类型引用。
答案 1 :(得分:0)
type T = Test1.specificTypes.Red
没有分配类型。它尝试将值指定为类型,当然不会编译。
这个怎么样?
object Test1 extends App {
object specificTypes extends Enumeration {
type specificTypes = Value
val Red = Value
val Green = Value
val Blue = Value
}
abstract class outer {
type T <: Test1.specificTypes.Value
def pr(w: T)
}
class red extends outer {
type T = Test1.specificTypes.Red.type //IMPORTANT THING!
def pr(w: T) = println("hello red")
}
class blue extends outer {
type T = Test1.specificTypes.Blue.type //IMPORTANT THING!
def pr(w: T) = println("hello blue")
}
val r = new red
//r.pr(Test1.specificTypes.Blue) // compilation error
/*
Error:(23, 28) type mismatch;
found : Test1.specificTypes.Blue.type (with underlying type Test1.specificTypes.Value)
required: Test1.r.T
(which expands to) Test1.specificTypes.Red.type
r.pr(Test1.specificTypes.Blue)
*/
val b = new blue
b.pr(Test1.specificTypes.Blue) // compiles, prints hello blue
}
但是,对于你的情况(就像你提到的那样)
我有一些类型的类,我想区分模式匹配中的类别
我会使用一个简单的sealed trait,就像Chobeat的回答一样。