scala - A<:< SomeType parameter declaration

标签 scala function

查看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 a Function1

<:<定义为:

sealed abstract class <:<[-From, +To] extends (From => To) with Serializable

这是 Function1[From, To] 的派生词,这就是您看到的 applyandThen来自。 <:<表示通用参数类型约束,其中 TOption[Int] 的子类型.

一般来说,<:<旨在用作强制隐式证据位于范围内的类型约束:

An instance of A <:< B witnesses that A is a subtype of B. Requiring an implicit argument of the type A <:< B encodes the generalized constraint A <: 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/

相关文章:

java - 如何在 lift JSON 中序列化和反序列化 Java 8 dateTime?

json - 数据帧Spark Scala爆炸了JSON数组

scala - 在 Apache Spark DataFrame 中,如何删除所有非 None 值都相同的所有列?

mysql - 创建返回 Mysql 数据的自定义 Excel 函数

function - 在函数中实现代码时的 setTimeout 问题

algorithm - 在 Matlab 中绘制轮廓图需要帮助

scala - 使用多态 ADT 类型检查的错误 Scala 代码

scala - 消除与父类(super class)的类字段同名的构造函数参数的歧义

java - Java 如何内联越过虚函数边界?

c++ - 模拟静态/全局函数的最佳简单方法?