相关疑难解决方法(0)

强制类型差异

在Scala中,我可以在编译时强制执行类型相等.例如:

case class Foo[A,B]( a: A, b: B )( implicit ev: A =:= B )

scala> Foo( 1, 2 )
res3: Foo[Int,Int] = Foo(1,2)

scala> Foo( 1, "2" )
<console>:10: error: Cannot prove that Int =:= java.lang.String.
Run Code Online (Sandbox Code Playgroud)

有没有办法强制执行类型A和类型B应该是不同的?

types scala

57
推荐指数
5
解决办法
4899
查看次数

在scala中键入类型不等式的约束

可能重复:
强制类型差异

由于存在一个在scala中强制执行相等的通用类型约束=:=,是否有一个对类型强制执行"不等于"?基本上!=但对于类型?

编辑

下面的评论指出现有的问答,答案似乎是(1)不,它不在标准库中(2)是的,可以定义一个.

所以我会修改我的问题,因为在看到答案之后我想到了一个想法.

鉴于现有解决方案:

sealed class =!=[A,B]

trait LowerPriorityImplicits {
  implicit def equal[A]: =!=[A, A] = sys.error("should not be called")
}
object =!= extends LowerPriorityImplicits {
  implicit def nequal[A,B](implicit same: A =:= B = null): =!=[A,B] = 
    if (same != null) sys.error("should not be called explicitly with same type")
    else new =!=[A,B]
}     

case class Foo[A,B](a: A, b: B)(implicit e: A =!= B)
Run Code Online (Sandbox Code Playgroud)

如果A <: B或者A >: B …

type-systems scala

4
推荐指数
1
解决办法
1925
查看次数

如何在Scala中使用否定类型?

我想做这样的事情:

def iDontLikeStrings(arg: Not[String]) = {....}
Run Code Online (Sandbox Code Playgroud)

基本上,这应该编译:

iDontLikeStrings(23) 
iDontLikeStrings(true)
Run Code Online (Sandbox Code Playgroud)

这不应该编译:

iDontLikeStrings("hello") 
Run Code Online (Sandbox Code Playgroud)

type-systems scala

4
推荐指数
1
解决办法
372
查看次数

标签 统计

scala ×3

type-systems ×2

types ×1