类型参数子句中的广义约束?

问题描述 投票:1回答:1

[SLS将type parameter clause的语法指定为

TypeParamClause   ::=  ‘[’ VariantTypeParam {‘,’ VariantTypeParam} ‘]’
FunTypeParamClause::=  ‘[’ TypeParam {‘,’ TypeParam} ‘]’
VariantTypeParam  ::=  {Annotation} [‘+’ | ‘-’] TypeParam
TypeParam         ::=  (id | ‘_’) [TypeParamClause] [‘>:’ Type] [‘<:’ Type] {‘<%’ Type} {‘:’ Type}                  {‘<%’ Type} {‘<%’ Type}

我们看到>:<:<%<%:作为类型形参子句中允许的保留名称。有没有一种方法可以在类型参数子句中使用generalised type constraint符号名<:<=:=,例如

def f[T =:= 42] = ???

将扩展为

def f[T](implicit ev: T =:= 42) = ???

类似于上下文绑定

def f[T: Numeric] = ???

扩展到

def f[T](implicit ev: Numeric[T]) = ???
scala type-parameter type-constraints
1个回答
0
投票

在2.13(如果您对约束单例感到好奇,它支持单例类型),您可以执行以下操作:

@ import $plugin.$ivy.`org.typelevel:kind-projector_2.13.1:0.11.0`
import $plugin.

@ type a = 23
defined type a

@ def f[N : * =:= a]: Unit = ()
defined function f

@ f[a]


@ f[23]


@ f[25]
cmd9.sc:1: Cannot prove that 25 =:= Int(23).
val res9 = f[25]
            ^
Compilation Failed

@ def g[N : * =:= 16]: Unit = ()
defined function g

@ g[16]


@ g[23]
cmd11.sc:1: Cannot prove that 23 =:= 16.
val res11 = g[23]
             ^
Compilation Failed

所以,是的,似乎有可能。您只需要使用同类的投影仪即可应用第二个参数。

<:<应该是同一故事:

@ def h[N : * <:< 16]: Unit = ()
defined function h

@ h[16]


@ h[17]
cmd13.sc:1: Cannot prove that 17 <:< 16.
val res13 = h[17]
             ^
Compilation Failed
© www.soinside.com 2019 - 2024. All rights reserved.