具有类型参数限制的Scala通用类的条件方法 [英] Conditional methods of Scala generic classes with restrictions for type parameters

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

问题描述

我相信泛型类只有在其类型参数符合某些附加限制的情况下才可以使它的一种方法可用,例如(当场即兴使用的语法):

I believe that a generic class may make one of its methods available only assuming that its type parameters conform to some additional restrictions, something like (syntax improvised on the spot):

trait Col[T] extends Traversable[T] {
    def sum[T<:Int] :T = (0/:this)(_+_)
}

我想我可以使用隐式参数作为证据...对此是否有语言功能?

I guess I could use implicit parameters as evidence... Is there a language feature for this?

推荐答案

在这种情况下,您只能使用隐式参数,因为类型是在方法调用之前确定的.

In this case you can only use an implicit parameter, as the type gets determined before the method call.

trait Col[T] extends Traversable[T] {
  def sum(implicit num: Numeric[T]) :T = ???
}

如果要调用的方法将被参数化,则可以使用上下文绑定,它只是绑定到类型参数的隐式参数的语法糖:

If the method you are calling would be parameterized, you could use context bounds, which are just syntactic sugar for the implicit parameter bound to the type parameter:

def foo[A](implicit ev: Something[A]) = ???

等同于

def foo[A : Something] = ???

这篇关于具有类型参数限制的Scala通用类的条件方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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