Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/hibernate/5.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
Scala:可以对两种类型中的一种强制执行类型参数吗?_Scala - Fatal编程技术网

Scala:可以对两种类型中的一种强制执行类型参数吗?

Scala:可以对两种类型中的一种强制执行类型参数吗?,scala,Scala,在下面的语句中,类型参数A必须是另一个类的子类: trait MyClass[A <: AnotherClass] { ... } trait MyClass[A根据您的评论,这对您有什么好处 sealed trait Entity[T] { def id: T; def id_=(v: T): Unit } trait UnmodifiableEntity extends Entity[String] trait ModifiableEntity extends Entity[Opti

在下面的语句中,类型参数
A
必须是另一个类的子类

trait MyClass[A <: AnotherClass] { ... }

trait MyClass[A根据您的评论,这对您有什么好处

sealed trait Entity[T] { def id: T; def id_=(v: T): Unit }
trait UnmodifiableEntity extends Entity[String]
trait ModifiableEntity extends Entity[Option[String]]

您可以使用
和隐式转换来获得(在我看来)接近您想要的东西

trait Entity[T] {
  def id: Either[T, Option[T]]
  def id_=(v: Either[T, Option[T]]): Unit
}

object Entity {
  implicit def toLeftEither[T](t: T): Either[T, Option[T]] = Left(t)
  implicit def toRightEither[T](t: Option[T]): Either[T, Option[T]] = Right(t)

  implicit def fromLeftEither[T](e: Either[T, Option[T]]): T = e.left.get
  implicit def frommRightEither[T](e: Either[T, Option[T]]): Option[T] = e.right.get
}
现在用法:

import Entity._

class E[T] extends Entity[T] {
  private[this] var _id: Either[T, Option[T]] = Right(Option.empty[T])
  def id =  _id
  def id_=(v: Either[T, Option[T]]): Unit = {_id = v}
}

val e = new E[String]
e.id = "1"

val a = e.id // a is of type Either[String, Option[String]]
val b: String = e.id
e.id = Some("1")
val c: Option[String] = e.id

e.id match {
  case Left(id) =>
  case Right(Some(id)) =>
  case _ =>
}
但是你必须小心不要混用类型,即

e.id = "1"
val c: Option[String] = e.id

将抛出
java.util.NoSuchElementException:any.left.value在右边

处理
字符串和
选项[String]
的实际用例是什么?我需要定义这样一个特征:
特征实体[T]{def id:T;def id=(v:T):Unit}
其中
T
选项[String]
用于可修改的实体或
字符串
用于不可修改的实体。您可以使用字符串/Option[String]语义介绍您自己的类型可能与旧博客中想法的某些实现重复::/不完全的隐式转换给我溃疡