比较 Scala 中的类型 [英] Compare types in Scala

查看:48
本文介绍了比较 Scala 中的类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个对象,每个对象都有本地定义的类型,我想确定类型是否相同.例如,我希望编译此代码:

I have two objects, each with locally defined types, and I want to determine if the types are the same. For example, I'd like this code to compile:

trait Bar {
  type MyType
}

object Bar {
  def compareTypes(left: Bar, right: Bar): Boolean = (left.MyType == right.MyType)
}

但是,编译失败并显示值 MyType 不是 Bar 的成员".

However, compilation fails with "value MyType is not a member of Bar".

这是怎么回事?有没有办法做到这一点?

What's going on? Is there a way to do this?

推荐答案

你可以这样做,但需要一些额外的机器:

You can do this, but it takes a little extra machinery:

trait Bar {
  type MyType
}

object Bar {
  def compareTypes[L <: Bar, R <: Bar](left: L, right: R)(
    implicit ev: L#MyType =:= R#MyType = null
  ) = ev != null
}

现在,如果我们有以下内容:

Now if we have the following:

val intBar1 = new Bar { type MyType = Int }
val intBar2 = new Bar { type MyType = Int }
val strBar1 = new Bar { type MyType = String }

它按预期工作:

scala> Bar.compareTypes(intBar1, strBar1)
res0: Boolean = false

scala> Bar.compareTypes(intBar1, intBar2)
res1: Boolean = true

诀窍是要求 L#MyTypeR#MyType 相同的隐式证据,并提供一个默认值(null代码>) 如果不是.然后你可以检查你是否得到了默认值.

The trick is to ask for implicit evidence that L#MyType and R#MyType are the same, and to provide a default value (null) if they aren't. Then you can just check whether you get the default value or not.

这篇关于比较 Scala 中的类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆