类型构造函数以适当的类型为界 [英] Type constructor bounded by proper type

查看:61
本文介绍了类型构造函数以适当的类型为界的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

请考虑以下类型参数子句 [F [_]< ;: Int] in

Consider the following type parameter clause [F[_] <: Int] in

def h[F[_] <: Int] = ???

其中类型构造函数 F 由正确的类型 Int 限制.现在 h [List] h [Int] 都是非法的

where a type constructor F is bounded by the proper type Int. Now both h[List] and h[Int] are illegal

scala> def h[F[_] <: Int] = ???
     |
def h[F[_] <: Int]: Nothing

scala> h[List]
        ^
       error: type arguments [List] do not conform to method h's type parameter bounds [F[_] <: Int]

scala> h[Int]
         ^
       error: Int takes no type parameters, expected: 1

那么为什么 [F [_]< ;: Int] 是合法的?

推荐答案

类型参数声明 F [_]< ;: Int 表示 F的每个实例 必须是 Int 的子类型.语法正确,尽管很隐秘: F 不必是 Int 的子类型; F [_] 必须是 Int 的子类型(对于可能放置在 _ 中的所有类型).这样的 F 的示例总是返回 Int :

The type parameter declaration F[_] <: Int means that every instantiation of F must be a subtype of Int. It's right in the syntax, though cryptic: F does not have to be a subtype of Int; F[_] has to be a subtype of Int (for all types that may be placed in the _). An example of such an F is one which always returns Int:

type ConstInt[X] = Int
h[ConstInt] // compiles

请注意,您可以在 _ 中命名类型.例如.我可以声明类型参数 F [X]< ;: X . X 对声明而言是局部的,通过在左侧的 F 下显示,在右侧用作边界并随后超出范围来定义.此示例意味着 F [X] 必须是 X 的子类型,例如就像

Note that you can name the type in the _. E.g. I can declare a type parameter F[X] <: X. X is local to the declaration, defined by appearing under F on the left, used as a bound on the right, and going out of scope afterwards. This example means that F[X] must be a subtype of X, e.g. as in

def f[F[X] <: X] = ???
type Identity[X] = X
f[Identity] // works
type ConstNothing[X] = Nothing
f[ConstNothing] // works
// f[ConstInt] (ConstInt[X] = Int is not always a subtype of X; counterexample X = AnyRef)

也许驾车回家了,边界应该是什么意思.

Perhaps that drives home what the bound is supposed to mean.

这篇关于类型构造函数以适当的类型为界的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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