TraversableOnce
には、sum
含まれている型が である場合にのみ使用できるメソッドがありNumeric
ます (それ以外の場合はコンパイルされません)。これは他のケースでも使用できるのでしょうか (実行時チェックを回避するため)。
特に、2 つのトレイト A と B がある場合です。オブジェクトが A と B の両方f
を継承する場合にのみ使用できるメソッドが必要ですが、一方だけを継承する場合はそうではありません。もう作りたくない。両方の特性が継承されていない場合は使用できないようにしたいだけです。trait AB extends A with B
f
package com.example
trait Base
trait Foo extends Base {
def g = println("foo bar " + toString)
}
trait Bar extends Base {
/* If this is both Foo and Bar, I can do more */
def f = {
if (!this.isInstanceOf[Foo]) error("this is not an instance of Foo")
this.asInstanceOf[Foo].g
}
}
object Test {
def main(args: Array[String]): Unit = {
object ab extends Foo with Bar
object ba extends Bar with Foo
object b extends Bar
ab.f
ba.f
// I don't want next line to compile:
try { b.f } catch { case e: RuntimeException => println(e) }
}
}
編集:@Aaron Novstrupのおかげで解決策
trait Bar extends Base { self =>
def f(implicit ev: self.type <:< Foo) = {
//self.asInstanceOf[Foo].g // [1]
ev(this).g // [2]
}
}
main
では、コンパイルされb.f
ません。良い
EDIT 2: 行 [1] を [2] に変更し、@Aaron Novstrup による回答の変更を反映
編集 3: self
@Aaron Novstrup による回答の反映変更を使用せずに
trait Bar extends Base {
/* If this is both Foo and Bar, I can do more */
def f(implicit ev: this.type <:< Foo) = {
ev(this).g
}
}