Scala的参数列表中将直接支持元组拆包吗? [英] Will tuple unpacking be directly supported in parameter lists in Scala?

查看:177
本文介绍了Scala的参数列表中将直接支持元组拆包吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Haskell中,您可以编写:

In Haskell you can write:

x :: (Int,Int) -> Int
x (p,s) = p

在Scala中,您将编写:

In Scala you would write:

def x(a: (Int, Int)) = a._1

或:

def x(a: (Int, Int)) = a match {
    case (p, s) => p
}

为什么没有类似的东西

def x(_: (p: Int, s: Int)) = p

def x(foo: (p @ Int, s @ Int)) = p

?

推荐答案

您要查找的功能称为 destructuring ,它的一般形式不仅限于元组拆包.我经常发现自己希望Scala拥有它,因为它是模式匹配语法的自然扩展:

The feature you're looking for is called destructuring and, in it's general form, would go well beyond just tuple unpacking. I've often found myself wishing that Scala had it since it's such a natural extension of the pattern matching syntax:

def first((f: Int, l: Int)) = f
def displayName(Person(first, last)) = last + ", " + first

解构 (以某种形式存在)以变量/值定义的形式出现:

Destructuring is (sort of) present in the form of variable/value definitions:

val (f, l) = tuple
val Person(first, last) = person

不幸的是,有一些类型 问题围绕我认为是这样的定义您不太可能很快就会在参数列表中看到破坏.

Unfortunately, there are some type safety issues around such definitions that I think make it unlikely that you'll see destructuring in parameter lists any time soon.

这篇关于Scala的参数列表中将直接支持元组拆包吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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