标量选项类型差异 [英] scala Option type difference

查看:85
本文介绍了标量选项类型差异的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

传递两个参数与传递一个参数有什么区别?

What is the difference between passing two arguments vs passing one argument?

val option1 = Option(String,String)
and
val option2 = Option(String)

推荐答案

当您编写类似Option(1, 2)的内容时,编译器首先将其除以Option.apply(1, 2),然后发现Option随播对象却没有.有一个带有两个参数的apply方法,它将自动将参数转换为元组:

When you write something like Option(1, 2), the compiler first desugars this to Option.apply(1, 2), and then when it sees that the Option companion object doesn't have an apply method that takes two arguments, it automatically converts the arguments into a tuple:

scala> Option(1, 2)
res0: Option[(Int, Int)] = Some((1,2))

它将对Option(1, 2, 3)Option(1, 2, 3, 4)等执行类似的操作.

It would do something similar for Option(1, 2, 3), Option(1, 2, 3, 4), etc.

这称为自动校正,仅适用于具有单个参数的方法.例如,以下内容将不会编译:

This is known as auto-tupling and only works for methods with a single argument. For example, the following won't compile:

scala> def foo[T](t: T, u: T): T = t
foo: [T](t: T, u: T)T

scala> foo(1, 2, 3)
<console>:13: error: too many arguments for method foo: (t: T, u: T)T
       foo(1, 2, 3)
          ^

此功能"是为了语法上的方便而提供的,它使Scala与其他函数语言(至少在元组和函数参数列表更统一的情况下)更加接近(至少以肤浅的方式).但是,很多人讨厌自动组合,因为这些东西实际上在Scala中并未统一,并且假装它们会导致混乱的代码和令人讨厌的错误消息.如果您是这些人之一(我是),则可以打开-Ywarn-adapted-args编译器标志,当编译器尝试执行此操作时,该标志会向您发出警告:

This "feature" is provided for syntactic convenience, and it brings Scala a little closer (at least in a superficial way) to other functional languages where tuples and function argument lists are more unified. Lots of people hate auto-tupling, though, because these things aren't actually unified in Scala, and pretending they are can lead to confusing code and annoying error messages. If you're one of these people (I am), you can turn on the -Ywarn-adapted-args compiler flag, which gives you warnings when the compiler tries to do this:

scala> Option(1, 2)
<console>:12: warning: Adapting argument list by creating a 2-tuple: this may not be what you want.
        signature: Option.apply[A](x: A): Option[A]
  given arguments: 1, 2
 after adaptation: Option((1, 2): (Int, Int))
       Option(1, 2)
             ^
res0: Option[(Int, Int)] = Some((1,2))

不过,这是一个品味问题.

This is a matter of taste, though.

这篇关于标量选项类型差异的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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