案例1:我的目标是当我们传递SampleClass类型时,getTypedOutput应该返回Result [Int]
trait SampleTrait[T]
trait Result[T]
class SampleClass extends SampleTrait[Int]
def getTypedOutput[C <: SampleTrait[T],T](clz : Class[C]) =
"".asInstanceOf[Result[T]] // dummy implementation
// here I want result should be Result[Int]
val out = getTypedOutput(classOf[SampleClass])
以上代码失败并出现以下错误
error: inferred type arguments [SampleClass,Nothing] do not conform to
method getTypedOutput's type parameter bounds [C <: SampleTrait[T],T]
val out = getTypedOutput(classOf[SampleClass])
^
Main.scala:18: error: type mismatch; found : Class[SampleClass](classOf[ScalaJSExample$$main$SampleClass]) required: Class[C]
val out = getTypedOutput(classOf[SampleClass])
http://www.scala-js-fiddle.com/gist/593a55f0f6b0f44c2e70?
案例2:
trait Result[T]
class SampleClass extends SampleTrait[Int]
trait SampleTrait[T] {
type ResultType = Result[T]
}
def getTypedOutput[C <: SampleTrait[_]](ctor: js.Dynamic): C#ResultType =
"".asInstanceOf[C#ResultType]
错误2:
Main.scala:20: error: type mismatch;
found : Result[(some other)_$1(in type C)]
required: Result[_$1(in type C)]
def getTypedOutput[C <: SampleTrait[_]](ctor: js.Dynamic): C#ResultType = "".asInstanceOf[C#ResultType]
答案 0 :(得分:4)
以下类型检查:
trait SampleTrait[T]
trait Result[T]
class SampleClass extends SampleTrait[Int]
object Test {
def getTypedOutput[T](clz: Class[_ <: SampleTrait[T]]): Result[T] =
"".asInstanceOf[Result[T]] // dummy implementation
def test(): Unit = {
val out = getTypedOutput(classOf[SampleClass])
val outCheck: Result[Int] = out
}
}