查看scala.Option[T]
来源我发现以下隐式参数声明 implicit ev: Null <:< A1
。自己尝试一下
class Test[T](val i: Int){
def test(p: T <:< Option[Int]) = 1
}
我发现p
看起来像 Function1
。它有apply
, andThen
等方法。如果我们这样写会有什么不同:
class TestMatch[T](val i: Int){
def test(p: T <:< Option[Int]) = //..
def test2(p: T => Option[Int]) = //...
}
test
的签名之间是否存在一些主要区别?和test2
?这个例子的行为是这样的:
tm.test2(x => { //fine
println(x)
Some(x)
})
tm.test(x => { //Compile error
println(x)
Some(x)
})
我也尝试过这个:
tm.test(x <:< { //Compile error
println(x)
Some(x)
})
但它也不起作用。如何使用test
?
最佳答案
I found that
p
looks like aFunction1
<:<
定义为:
sealed abstract class <:<[-From, +To] extends (From => To) with Serializable
这是 Function1[From, To]
的派生词,这就是您看到的 apply
和andThen
来自。 <:<
表示通用参数类型约束,其中 T
是 Option[Int]
的子类型.
一般来说,<:<
旨在用作强制隐式证据位于范围内的类型约束:
An instance of
A <:< B
witnesses thatA
is a subtype ofB
. Requiring an implicit argument of the typeA <:< B
encodes the generalized constraintA <: B
.
But couldn't you explain who creates this implicit <:< parameter? Where did it come from? I guess compiler's aware about <:< and know what to do with it
在您的示例中,没有创建隐式证据。您只需使用 <:<
作为类型,而不是约束。如果您想创建一个,您需要自己声明隐式:
def greaterThan[T](x: T, y: T)(implicit ev: T <:< Ordered[T]): Boolean = x > y
关于scala - A<:< SomeType parameter declaration,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38943289/