型パラメータ句内の一般制約?

マリオGalic:

SLS指定構文の型パラメータ句として

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

私たちが見るところ>:<:<%<%:などの型パラメータ句での予約名を可能にしました。私たちが使用できる方法がある一般型制約シンボル名を<:<=:=そのようなタイプのパラメータ句には、

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

に拡大します

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

コンテキストバインドする方法に似て

def f[T: Numeric] = ???

膨張するまで

def f[T](implicit ev: Numeric[T]) = ???
マシューKubuszok:

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

おすすめ

転載: http://10.200.1.11:23101/article/api/json?id=414467&siteId=1