Scala 类型声明中的哈希标记——`P#Backend#Database` 是什么意思?
Hashmark in Scala type declaration -- What does `P#Backend#Database` mean?
在 Slick 库中我们找到这个声明:
/** A configuration for a Database plus a matching Profile. */
trait DatabaseConfig[P <: BasicProfile] {
/** Get the configured Database. It is instantiated lazily when this method is called for the
* first time, and must be closed after use. */
def db: P#Backend#Database
}
P#Backend#Database
是什么意思? #
是做什么的?它是标准的 Scala 构造还是来自库的东西?
类型声明中的#
符号类似于普通代码中的.
:它指的是定义在类型内部的type。这是一个简化的例子:
trait Profile {
type Database
}
trait Config[P <: Profile] {
def db: P#Database
}
case class MyProfile() extends Profile {
type Database = String
}
case object MyConfig extends Config[MyProfile] {
def db = "mydatabase" // has the type MyProfile#Database, that is, String
}
如果我们将 db
的类型更改为其他类型:
case object MyConfig extends Config[MyProfile] {
def db = 123
}
存在解释类型含义的错误:
type mismatch;
found : Int(123)
required: MyProfile#Database
(which expands to) String
在 Slick 库中我们找到这个声明:
/** A configuration for a Database plus a matching Profile. */
trait DatabaseConfig[P <: BasicProfile] {
/** Get the configured Database. It is instantiated lazily when this method is called for the
* first time, and must be closed after use. */
def db: P#Backend#Database
}
P#Backend#Database
是什么意思? #
是做什么的?它是标准的 Scala 构造还是来自库的东西?
类型声明中的#
符号类似于普通代码中的.
:它指的是定义在类型内部的type。这是一个简化的例子:
trait Profile {
type Database
}
trait Config[P <: Profile] {
def db: P#Database
}
case class MyProfile() extends Profile {
type Database = String
}
case object MyConfig extends Config[MyProfile] {
def db = "mydatabase" // has the type MyProfile#Database, that is, String
}
如果我们将 db
的类型更改为其他类型:
case object MyConfig extends Config[MyProfile] {
def db = 123
}
存在解释类型含义的错误:
type mismatch;
found : Int(123)
required: MyProfile#Database
(which expands to) String