誰かがwith
タイプを定義する際にキーワードを使用する実際の例を説明して提供できますか?
タイプを定義しましょう
type T = A with B
どういう意味ですか?いつ使用する必要がありますか?タイプをインスタンス化する方法はT
?
タイプ接続詞と呼ばれていると思います。
これを使用して、特定のタイプが指定されたすべての特性/クラスを拡張する必要があることを強制できます。愚かな例:
scala> trait Quackable {
| def quack = println("quack")
| }
defined trait Quackable
scala> trait Walkable {
| def walk = println("walk")
| }
defined trait Walkable
scala> case class Duck(name: String) extends Quackable with Walkable
defined class Duck
scala> def foo(d: Quackable with Walkable): Unit = {
| d.quack
| d.walk
| }
foo: (d: Quackable with Walkable)Unit
scala> foo(Duck(""))
quack
walk
// Or you can create a type alias and use it.
scala> type QW = Quackable with Walkable
defined type alias QW
scala> def foo(d: QW): Unit = {
| d.quack
| d.walk
| }
foo: (d: QW)Unit
scala> foo(Duck(""))
quack
walk
// If you need to retain the type information for some reason, you can use a type parameter.
scala> def foo[A <: Quackable with Walkable](d: A): A = {
| d.quack
| d.walk
| d
| }
foo: [A <: Quackable with Walkable](d: A)A
scala> foo(Duck(""))
quack
walk
res1: Duck = Duck()
「インスタンス化する方法」については、そのように考えないでください。type
タイプエイリアス/シノニム/関数を作成します。これらは必ずしも具体的なインスタンス化可能なタイプを表すとは限りません。
編集:
Javaに精通している場合は、with
上記で使用されているように、Javaのに似ています&
。
public static <QW extends Quackable & Walkable> void foo(QW d) {
d.quack();
d.walk();
}
ただし、Javaとは異なり&
、with
適切な型を提供します。私が書いた最初の定義はfoo
Javaに翻訳できません。また、Javaでは次のことはできません&
。
scala> case object Quackawalkasaurus extends Quackable with Walkable
defined module Quackawalkasaurus
scala> List(Duck(""), Quackawalkasaurus)
res2: List[Product with Serializable with Quackable with Walkable] = List(Duck(), Quackawalkasaurus)
// Add an explicit type annotation if you want to remove unwanted common super-traits/classes.
scala> List(Duck(""), Quackawalkasaurus) : List[Quackable with Walkable]
res3: List[Quackable with Walkable] = List(Duck(), Quackawalkasaurus)