Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/mysql/65.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
在Java或Scala中,如何根据是否满足类型绑定来定义条件控制流?_Scala_Pattern Matching_Type Bounds - Fatal编程技术网

在Java或Scala中,如何根据是否满足类型绑定来定义条件控制流?

在Java或Scala中,如何根据是否满足类型绑定来定义条件控制流?,scala,pattern-matching,type-bounds,Scala,Pattern Matching,Type Bounds,在scala中,我有一个类定义: class A[T >: Null]{} 以及一个可选创建实例的函数: def use[T](): Option[A[T]] 现在我想对其进行如下定义: 如果不满足条件T>:Null,则返回None 如果满足,则返回一些[A[T]] 在这种情况下,如何编写函数使用?这是使用类型类的方法 def use[T]()(implicit sel: Selector[T]): sel.Out = sel.x trait Selector[T] { ty

在scala中,我有一个类定义:

class A[T >: Null]{}
以及一个可选创建实例的函数:

def use[T](): Option[A[T]]
现在我想对其进行如下定义:

  • 如果不满足条件
    T>:Null
    ,则返回None
  • 如果满足,则返回一些[A[T]]

在这种情况下,如何编写函数
使用

这是使用类型类的方法

def use[T]()(implicit sel: Selector[T]): sel.Out = sel.x

trait Selector[T] {
  type Out
  val x: Out
}

trait LowPrioritySelector {
  implicit def default[T]: Selector[T] { type Out = None.type } = new Selector[T] {
    override type Out = None.type
    override val x: Out = None
  }
}

object Selector extends LowPrioritySelector {
  implicit def superTypeOfNull[T >: Null]: Selector[T] { type Out = Some[A[T]] } = new Selector[T] {
    override type Out = Some[A[T]]
    override val x: Out = Some(new A[T])
  }
}

use[String]() // Some(App$A@34340fab)   
use[Int]() // None

这是一种类型类的方法

def use[T]()(implicit sel: Selector[T]): sel.Out = sel.x

trait Selector[T] {
  type Out
  val x: Out
}

trait LowPrioritySelector {
  implicit def default[T]: Selector[T] { type Out = None.type } = new Selector[T] {
    override type Out = None.type
    override val x: Out = None
  }
}

object Selector extends LowPrioritySelector {
  implicit def superTypeOfNull[T >: Null]: Selector[T] { type Out = Some[A[T]] } = new Selector[T] {
    override type Out = Some[A[T]]
    override val x: Out = Some(new A[T])
  }
}

use[String]() // Some(App$A@34340fab)   
use[Int]() // None

除了基元类型之外,所有类型都是
Null
的超类型。我不清楚你到底想在这里做什么,但你试过typeclass吗?或者可能只是一个广义类型约束。这是在RowEncoder API未准备好时,尝试在Apache Spark中使用UserDefinedType。你介意举一个简短的例子吗?如果没有用例,很难提供一个例子,你能再解释一下你到底想要实现什么吗?
use[T]
是如何工作的。除了原语类型之外,所有的东西都是
Null
的超类型。我不清楚你到底想在这里做什么,但你试过typeclass吗?或者可能只是一个广义类型约束。这是在RowEncoder API未准备好时,尝试在Apache Spark中使用UserDefinedType。你介意举一个简短的例子吗?如果没有用例,很难提供一个例子,你能再解释一下你到底想要实现什么吗?
如何使用[T]
工作。