为什么在 Scala 中定义类型时得到 "expected class or object definition"?
Why do I get "expected class or object definition" when defining a type in scala?
如果我这样写(根据 docs 定义 Slick 表):
type UserIdentity = (String, String)
class UserIdentity(tag: Tag){
...
}
我收到编译错误:"expected class or object definition" 指向 type
声明。为什么?
您不能在 class、特征或对象定义之外定义类型别名。
如果你想要一个在包级别可用的类型别名(这样你就不必显式导入它),最简单的方法是定义一个 package object,它与包并允许您在其中定义任何内容,包括类型别名。
因此,如果您有一个 foo.bar
包并且您希望添加类型别名,请执行以下操作:
package foo
package object bar {
type UserIdentity = (String, String)
}
//in another file
package foo.bar
val x: UserIdentity = ...
如果我这样写(根据 docs 定义 Slick 表):
type UserIdentity = (String, String)
class UserIdentity(tag: Tag){
...
}
我收到编译错误:"expected class or object definition" 指向 type
声明。为什么?
您不能在 class、特征或对象定义之外定义类型别名。
如果你想要一个在包级别可用的类型别名(这样你就不必显式导入它),最简单的方法是定义一个 package object,它与包并允许您在其中定义任何内容,包括类型别名。
因此,如果您有一个 foo.bar
包并且您希望添加类型别名,请执行以下操作:
package foo
package object bar {
type UserIdentity = (String, String)
}
//in another file
package foo.bar
val x: UserIdentity = ...