在Scala中下划线的所有用途是什么?
我看了一些调查,发现了一个奇怪的问题:“。你能?如果是,请在此处填写。欢迎提供解释性示例。下面是对下划线用法的精彩解释 示例:在Scala中下划线的所有用途是什么?,scala,Scala,我看了一些调查,发现了一个奇怪的问题:“。你能?如果是,请在此处填写。欢迎提供解释性示例。下面是对下划线用法的精彩解释 示例: def matchTest(x: Int): String = x match { case 1 => "one" case 2 => "two" case _ => "anything other than one and two" } expr match { case List(1,_,_) =&g
def matchTest(x: Int): String = x match {
case 1 => "one"
case 2 => "two"
case _ => "anything other than one and two"
}
expr match {
case List(1,_,_) => " a list with three element and the first element is 1"
case List(_*) => " a list with zero or more elements "
case Map[_,_] => " matches a map with any key type and any value type "
case _ =>
}
List(1,2,3,4,5).foreach(print(_))
// Doing the same without underscore:
List(1,2,3,4,5).foreach( a => print(a))
在Scala中,导入包时,\
的行为类似于Java中的*
// Imports all the classes in the package matching
import scala.util.matching._
// Imports all the members of the object Fun (static import in Java).
import com.test.Fun._
// Imports all the members of the object Fun but renames Foo to Bar
import com.test.Fun.{ Foo => Bar , _ }
// Imports all the members except Foo. To exclude a member rename it to _
import com.test.Fun.{ Foo => _ , _ }
在Scala中,将为对象中的所有非私有变量隐式定义getter和setter。getter名称与变量名称相同,并且为setter名称添加了。=
class Test {
private var a = 0
def age = a
def age_=(n:Int) = {
require(n>0)
a = n
}
}
用法:
val t = new Test
t.age = 5
println(t.age)
如果尝试将函数分配给新变量,将调用该函数,并将结果分配给该变量。这种混淆是由于方法调用的可选大括号造成的。我们应该在函数名后使用u将其分配给另一个变量
class Test {
def fun = {
// Some code
}
val funLike = fun _
}
下面是对下划线用法的一个很好的解释 示例:
def matchTest(x: Int): String = x match {
case 1 => "one"
case 2 => "two"
case _ => "anything other than one and two"
}
expr match {
case List(1,_,_) => " a list with three element and the first element is 1"
case List(_*) => " a list with zero or more elements "
case Map[_,_] => " matches a map with any key type and any value type "
case _ =>
}
List(1,2,3,4,5).foreach(print(_))
// Doing the same without underscore:
List(1,2,3,4,5).foreach( a => print(a))
在Scala中,导入包时,\
的行为类似于Java中的*
// Imports all the classes in the package matching
import scala.util.matching._
// Imports all the members of the object Fun (static import in Java).
import com.test.Fun._
// Imports all the members of the object Fun but renames Foo to Bar
import com.test.Fun.{ Foo => Bar , _ }
// Imports all the members except Foo. To exclude a member rename it to _
import com.test.Fun.{ Foo => _ , _ }
在Scala中,将为对象中的所有非私有变量隐式定义getter和setter。getter名称与变量名称相同,并且为setter名称添加了。=
class Test {
private var a = 0
def age = a
def age_=(n:Int) = {
require(n>0)
a = n
}
}
用法:
val t = new Test
t.age = 5
println(t.age)
如果尝试将函数分配给新变量,将调用该函数,并将结果分配给该变量。这种混淆是由于方法调用的可选大括号造成的。我们应该在函数名后使用u将其分配给另一个变量
class Test {
def fun = {
// Some code
}
val funLike = fun _
}
除了JAiro提到的,我还喜欢这个:
def getConnectionProps = {
( Config.getHost, Config.getPort, Config.getSommElse, Config.getSommElsePartTwo )
}
如果某人需要所有连接属性,他可以执行以下操作:
val ( host, port, sommEsle, someElsePartTwo ) = getConnectionProps
如果您只需要一台主机和一个端口,可以执行以下操作:
val ( host, port, _, _ ) = getConnectionProps
除了JAiro提到的,我还喜欢这个:
def getConnectionProps = {
( Config.getHost, Config.getPort, Config.getSommElse, Config.getSommElsePartTwo )
}
如果某人需要所有连接属性,他可以执行以下操作:
val ( host, port, sommEsle, someElsePartTwo ) = getConnectionProps
如果您只需要一台主机和一个端口,可以执行以下操作:
val ( host, port, _, _ ) = getConnectionProps
我能想到的是 存在类型 高类类型参数 忽略的变量 忽略的参数 忽略自类型的名称 通配符模式 插值中的通配符模式 模式中的序列通配符 通配符导入 隐藏进口 给运营商的联名信 赋值运算符 占位符语法 方法值 将按名称调用参数转换为函数 默认初始值设定项 可能还有其他的我已经忘记了
显示为什么
foo()
和foo
不同的示例:
这个例子:
在第一种情况下,process
表示一种方法;Scala采用多态方法,并试图通过填充类型参数使其成为单态,但意识到没有可以为A
填充的类型将给出类型(=>Unit)=>?
(存在
不是类型)
在第二种情况下,进程()
是lambda;在编写没有显式参数类型的lambda时,Scala从foreach
期望的参数推断出类型,\u=>Unit
是一种类型(而纯\u
不是),因此可以替换和推断它
这可能是我在Scala遇到的最棘手的问题
请注意,此示例在2.13中编译。忽略它,就像它被分配给下划线一样。我能想到的是 存在类型 高类类型参数 忽略的变量 忽略的参数 忽略自类型的名称 通配符模式 插值中的通配符模式 模式中的序列通配符 通配符导入 隐藏进口 给运营商的联名信 赋值运算符 占位符语法 方法值 将按名称调用参数转换为函数 默认初始值设定项 可能还有其他的我已经忘记了
显示为什么
foo()
和foo
不同的示例:
这个例子:
在第一种情况下,process
表示一种方法;Scala采用多态方法,并试图通过填充类型参数使其成为单态,但意识到没有可以为A
填充的类型将给出类型(=>Unit)=>?
(存在
不是类型)
在第二种情况下,进程()
是lambda;在编写没有显式参数类型的lambda时,Scala从foreach
期望的参数推断出类型,\u=>Unit
是一种类型(而纯\u
不是),因此可以替换和推断它
这可能是我在Scala遇到的最棘手的问题
请注意,此示例在2.13中编译。忽略它,就像它被分配给下划线一样。来自中的(我的条目),我当然不能保证它是完整的(我两天前刚刚添加了两个条目):
导入scala。\通配符--导入所有scala
导入scala.{Predef=>\uu0,\u0}//异常,除Predef之外的所有内容
def f[M[]]//更高类型的类型参数
def(m:m[])//存在类型
_++//匿名函数占位符参数
m _//Eta方法到方法值的展开
m(_)//部分函数应用
_=>5//丢弃的参数
case=>//通配符模式--匹配任何内容
val(a,)=(1,2)//同样的事情
对于(我的条目)中的(),我当然不能保证完整(我两天前刚刚添加了两个条目):
导入scala。\通配符--导入所有scala
导入scala.{Predef=>\uu0,\u0}//异常,除Predef之外的所有内容
def f[M[]]//更高类型的类型参数
def(m:m[])//存在类型
_++//匿名函数占位符参数
m _//Eta方法到方法值的展开
m(_)//部分函数应用
_=>5//丢弃的参数
case=>//通配符模式--匹配任意项
import java.util._
import java.util.{ArrayList => _, _}
def bang_!(x: Int) = 5
def foo_=(x: Int) { ... }
List(1, 2, 3) map (_ + 2)
List(1, 2, 3) foreach println _
def toFunction(callByName: => Int): () => Int = callByName _
var x: String = _ // unloved syntax may be eliminated
trait PlaceholderExample {
def process[A](f: A => Unit)
val set: Set[_ => Unit]
set.foreach(process _) // Error
set.foreach(process(_)) // No Error
}
import scala._ // Wild card -- all of Scala is imported
import scala.{ Predef => _, _ } // Exception, everything except Predef
def f[M[_]] // Higher kinded type parameter
def f(m: M[_]) // Existential type
_ + _ // Anonymous function placeholder parameter
m _ // Eta expansion of method into method value
m(_) // Partial function application
_ => 5 // Discarded parameter
case _ => // Wild card pattern -- matches anything
val (a, _) = (1, 2) // same thing
for (_ <- 1 to 10) // same thing
f(xs: _*) // Sequence xs is passed as multiple parameters to f(ys: T*)
case Seq(xs @ _*) // Identifier xs is bound to the whole matched sequence
var i: Int = _ // Initialization to the default value
def abc_<>! // An underscore must separate alphanumerics from symbols on identifiers
t._2 // Part of a method name, such as tuple getters
1_000_000 // Numeric literal separator (Scala 2.13+)
List("foo", "bar", "baz").map(n => n.toUpperCase())
List("foo", "bar", "baz").map(_.toUpperCase())
val nums = List(1,2,3,4,5,6,7,8,9,10)
nums filter (_ % 2 == 0)
nums reduce (_ + _)
nums.exists(_ > 5)
nums.takeWhile(_ < 8)
type StringMatcher = String => (String => Boolean)
def starts: StringMatcher = (prefix:String) => _ startsWith prefix
def starts: StringMatcher = (prefix:String) => (s)=>s startsWith prefix