简体   繁体   English

Scala泛型-T具有方法限制

[英]Scala Generics - T has method restrictions

I am new with scala generics, I have read multiple articles about views, type bound/context bound. 我是scala泛型的新手,我已经阅读了多篇有关视图,类型绑定/上下文绑定的文章。 When I have tried to implement my class, I was really confused. 当我尝试实现我的课程时,我真的很困惑。

My question is, let's say I have a template class MyClass[T]{} . 我的问题是,假设我有一个模板类MyClass [T] {} I want that T must have some methods for example : 我希望T必须具有一些方法,例如:

def func1(t:T):T
def func2(t:T):Boolean
def func3(t:T):Unit

Note: classes that will use MyClass are not T therefore I cannot use :< or :> 注意:将使用MyClass的类不是T,因此我不能使用:<或:>

I have read about Ordered and Ordering that have implicit function, but I still cannot figure out how to implement it. 我已经阅读了有关具有隐式功能的Ordered和Ordering的信息,但是我仍然无法弄清楚如何实现它。

Thanks for helpers 谢谢帮手

You can do that with typeclasses. 您可以使用typeclass做到这一点。 Create a trait , that contains the methods you need and for every type that should be supported create an implicit instance: 创建一个trait ,其中包含所需的方法,并为应支持的每种类型创建一个隐式实例:

trait MyTypeClass[T] {
  def func1(t:T):T
  def func2(t:T):Boolean
  def func3(t:T):Unit
}

implicit object MyTypeClassInt extends MyTypeClass[Int] {
  def func1(t:Int) = t + 2
  def func2(t:Int) = t > 4
  def func3(t:Int) = println(s"t is: $t")
}

Now if you add a context bound to the type parameter in your class, it can only be instantiated, when an instance for the given type is in scope. 现在,如果您在类中添加了绑定到类型参数的上下文,则只有当给定类型的实例在范围内时,才能实例化该上下文。

class MyClass[A : MyTypeClass](a: A)

scala> new MyClass(2)
res0: MyClass[Int] = MyClass@47825164

scala> new MyClass("")
<console>:11: error: could not find implicit value for evidence parameter of type MyTypeClass[String]
              new MyClass("")**

You can access the instance in your class by calling implicitly[MyTypeClass[A]] . 您可以通过implicitly[MyTypeClass[A]]调用implicitly[MyTypeClass[A]]来访问类中的实例。 Alternatively you can do one of the following things: 或者,您可以执行以下任一操作:

1.) Instead of using a context bound add an implicit parameter to your class: 1.)代替使用上下文绑定,将隐式参数添加到您的类中:

class MyClass[A](a: A)(implicit ev: MyTypeClass[A])

2.) Add a companion for your typeclass, that has an apply method, that implicitly retrieves the instance and returns it: 2.)为您的类型类添加一个同伴,该同伴具有一个apply方法,该同伴隐式地检索该实例并将其返回:

object MyTypeClass {
  def apply[A](implicit ev: MyTypeClass[A]) = ev
}

and use it in your class like this: 并在您的班级中像这样使用它:

MyTypeClass[A].func1(a)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM