见证抽象类型实现类型类 [英] Witness that an abstract type implements a typeclass

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

问题描述

我相信我对此的理解是正确的,但我想检查一下.创建类型类时,让它们采用单个类型参数(如TypeClass[A])感觉很整洁.如果需要以其他方式对typeclass进行参数化,则可以使用抽象类型,这里将两种方法进行比较: 抽象类型与类型参数

I believe my understanding on this is correct but I'd like to check. When creating typeclasses, it feels neater to have them take a single type parameter, like TypeClass[A]. If the typeclass needs to be parameterized in other ways, abstract types can be used, and there is a comparison of the two approaches here: Abstract types versus type parameters

据我所知,链接中未提及的一件事是,如果使用类型参数,则可以看到该参数实现了(不同的)类型类,例如:

So far as I have been able to figure out, one thing which is not mentioned in the link is that if using a type parameter, you can witness that the parameter implements a (different) typeclass, likeso:

trait IsValidForTC[A]
    
abstract class TCWithTypeParam[A, B] (implicit ev: IsValidForTC[B]) {} 

如果我使用抽象类型,则不能确定它实现了IsValidForTC:

If I use an abstract type, I cannot be sure that it implements IsValidForTC:

abstract class TCWithAbstractType[A] (implicit ev: IsValidForTC[B]) {
    type B
} //not found: Type B

如果是这样,那么这是有道理的,但是上面的链接中没有提到这种区别,所以我想检查一下.

If so then this makes sense, but this difference isn't mentioned in the link above so I'd like to check.

谢谢!

推荐答案

是将隐式约束放在类级别还是方法级别上,这是您的选择.这将影响解析隐式的时间.

It's your choice whether to put implicit constraints on class level or method level. This makes impact on when the implicits are resolved.

在具有隐式参数的类型参数类型类中,您不限制类型类的类型(应用于类型参数),即,即使作用域中没有隐式IsValidForTC[B],也可以使用类型TCWithTypeParam[A, B] .您要约束的是类型类的构造函数.您可以通过以下方式为类型成员类型类模拟此行为.将构造函数设为私有,并在具有所需隐式约束的伴侣对象中定义apply方法(有时称为instance)

In a type-parameter type class with implicit parameter you don't constrain the type of type class (applied to type parameters), i.e. type TCWithTypeParam[A, B] can be used even if there is no implicit IsValidForTC[B] in a scope. What you do constrain is the constructor of type class. You can emulate this behavior for type-member type class in the following way. Make the constructor private and define apply method (or instance as it's called sometimes) in companion object with desired implicit constraint

abstract class TCWithAbstractType[A] private {
  type B
}

object TCWithAbstractType {
  def apply[A, _B: IsValidForTC]: TCWithAbstractType[A] { type B = _B } = 
    new TCWithAbstractType[A] { type B = _B }
}

这篇关于见证抽象类型实现类型类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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