> 2类型参数的Scala中缀类型别名? [英] Scala infix type aliasing for >2 type parameters?

查看:115
本文介绍了> 2类型参数的Scala中缀类型别名?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道在Scala中,您可以执行type ===>[A, B] = Map[A, B],然后可以使用中缀符号来定义def foo: String ===> Int,这与说def foo: Map[String, Int]相同.有什么方法可以利用此前缀表示法创建具有> 2个参数的类型?例如,我想要这样的东西:

I know in Scala, you can do type ===>[A, B] = Map[A, B] and then you can use infix notation to define def foo: String ===> Int which is same as saying def foo: Map[String, Int]. Is there any way to exploit this infix notation to create types with >2 arguments? For example, I want something like this:

type A ~> B ~~~> C是say Map[A, Pair[B, C]]的别名?

无论如何,我可以在这行中写点东西:

Is there anyway I can write something line this:

type A to B -> C作为(A, B, C)类型的别名?

推荐答案

有趣地

Interestingly operator precedence as defined for symbolic methods doesn't seem to hold for symbolic type aliases. Instead infix type aliases are always evaluated left associative:

type -[A,B] = Map[A,B] 
type /[A,B] = Map[A,B] // '/' has higher precedence than '-' as an operator
classOf[A - B / C] // Class[/[-[A,B],C]]
classOf[A / B - C] // Class[-[/[A,B],C]]

不幸的是,这意味着没有这样的括号,您将永远无法做您想要的事情:

Unfortunately that means it will never be possible to do what you ask for without parentheses like this:

classOf[A - (B / C)] // Class[-[A,/[B,C]]

因此,最接近的答案如下:

So the closest answer is the following:

type ~>[A,B] = Map[A,B]
type ~~~>[A,B] = Pair[A,B]
classOf[A ~> (B ~~~> C)] // Map[A,Pair[B,C]]

仅当您使用右关联别名(以:结尾)时,才可以省略括号

Ommitting the parentheses will only be possible if you use right associative aliases (ending with :)

type ~:[A,B] = Map[A,B]
type ~~~:[A,B] = Pair[A,B]
classOf[A ~: B ~~~: C] // Map[A,Pair[B,C]]

再次,不幸的是,由于所有类型别名具有相同的优先级,因此不可能在没有括号的情况下混合左右联想别名.

Again, unfortunately since all type aliases have the same precedence it is not possible to mix right and left associative aliases without parentheses.

关于问题的第二部分:(A,B,C)Tuple3[A,B,C]的语法糖,它是具有三个参数的类型.由于中缀类型仅带有两个参数,因此我担心没有办法仅用中缀类型来表示此类型.您总是会最终嵌套两个参数类型(例如(A,(B,C))((A,B),C).

Concerning the second part of your question: (A,B,C) is syntactic sugar for Tuple3[A,B,C] which is a type with three parameters. As infix types only take two parameters, I'm afraid that I believe there is no way to represent this type solely with infix types. You would always end up with nested two parameter types (e.g. (A,(B,C)) or ((A,B),C).

这篇关于> 2类型参数的Scala中缀类型别名?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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