您的位置:首页 > 其它

scala符号<:和: =>以及_*等

2017-06-11 23:03 309 查看

1.(1)函数传名调用(call-by-name)符号:
=>名字作为一个参数

(2)R
<: { def close():Unit }继承,R是子类,这里继承方法close():Unit

例子

objectmanage {
def apply[R <: { def close():Unit },T](resource: => R)(f: R => T): T = {
var res: Option[R] = None
try {
res = Some(resource)         // Only reference "resource"once!!
f(res.get)                   // Return the T instance
} catch {
case NonFatal(ex) =>
println(s"manage.apply(): Nonfatal exception! $ex")
throw ex
} finally {
if (res != None) {
println(s"Closingresource...")
res.get.close
}
}
}
}

objectTryCatchARM {
/** Usage: scala rounding.TryCatch filename1filename2 ... */
def main(args: Array[String]) = {
val sizes = args map (arg =>returnFileLength(arg))
println("Returned sizes: " +(sizes.mkString(", ")))
}

import scala.io.Source

def returnFileLength(fileName: String): Int ={
println() // Add a blank line for legibility
manage(Source.fromFile(fileName)) { source=>
val size = source.getLines.size
println(s"file $fileName has $sizelines")
if (size > 200) throw newRuntimeException(s"Big file: $fileName!")
size
}
}
}


2.case +:(head, tail)或者

case head+:tail

1.(1)函数传名调用(call-by-name)符号:
=>名字作为一个参数

(2)R
<: { def close():Unit }继承,R是子类,这里继承方法close():Unit

例子

3 Types with two typeparameters(两个类型参数) can be written withinfix notation(中缀表示)

case classWith[A,B](a: A, b: B)
//val fw1 ="Foo" With 1       // Doesn'twork
// Butnotice the following type annotations:
val with1:With[String,Int] = With("Foo", 1)
val with2:String With Int  = With("Bar",2)

List(with1,with2, "test","today") foreach { w =>

w match {
case s With i => println(s"$s with$i")
case v => println(s"Unknown:$w")
}
}

4. _*其余的变量参数, 参数序列

valnonEmptyList   = List(1, 2, 3, 4, 5)                             // <1>
valemptyList      = Nil
valnonEmptyMap    = Map("one"-> 1, "two" -> 2, "three" -> 3)

// Processpairs

defwindows[T](seq: Seq[T]): String = seq match {

case Seq(head1, head2, _*) =>                                      //<2>
s"($head1, $head2), " +windows(seq.tail)                       // <3>
case Seq(head, _*) =>
s"($head, _), " +windows(seq.tail)                             // <4>
case Nil => "Nil"
}

for (seq<- Seq(nonEmptyList, emptyList, nonEmptyMap.toSeq)) {
object Opextends Enumeration {                                      //<1>
type Op = Value
val EQ  = Value("=")
val NE  = Value("!=")
val LTGT = Value("<>")
val LT  = Value("<")
val LE  = Value("<=")
val GT  = Value(">")
val GE  = Value(">=")
}

import Op._

//Represent a SQL "WHERE x op value" clause, where +op+ is a
// comparisonoperator: =, !=, <>, <, <=, >, or >=.
case classWhereOp[T](columnName: String, op: Op, value: T)          // <2>

//Represent a SQL "WHERE x IN (a, b, c, ...)" clause.

case classWhereIn[T](columnName: String, val1: T, vals: T*)         // <3>

val wheres= Seq(                                                   // <4>
WhereIn("state", "IL","CA", "VA"),
WhereOp("state", EQ,"IL"),
WhereOp("name", EQ, "BuckTrends"),
WhereOp("age", GT, 29))

for (where<- wheres) {

where match {
case WhereIn(col, val1, vals @ _*)=>                            //<5>
val valStr = (val1 +:vals).mkString(", ")
println (s"WHERE $col IN($valStr)")
case WhereOp(col, op, value) => println(s"WHERE $col $op $value")
case _ => println (s"ERROR: Unknownexpression: $where")
}
}
println(windows(seq))}




5. @ _*变量参数列表, vals: T*变长参数

object Op extends Enumeration {                                      // <1>
type Op = Value

val EQ   = Value("=")
val NE   = Value("!=")
val LTGT = Value("<>")
val LT   = Value("<")
val LE   = Value("<=")
val GT   = Value(">")
val GE   = Value(">=")
}
import Op._

// Represent a SQL "WHERE x op value" clause, where +op+ is a
// comparison operator: =, !=, <>, <, <=, >, or >=.
case class WhereOp[T](columnName: String, op: Op, value: T)          // <2>

// Represent a SQL "WHERE x IN (a, b, c, ...)" clause.
case class WhereIn[T](columnName: String, val1: T, vals: T*)         // <3>

val wheres = Seq(                                                    // <4>
WhereIn("state", "IL", "CA", "VA"),
WhereOp("state", EQ, "IL"),
WhereOp("name", EQ, "Buck Trends"),
WhereOp("age", GT, 29))

for (where <- wheres) {
where match {
case WhereIn(col, val1, vals @ _*) =>                            // <5>
val valStr = (val1 +: vals).mkString(", ")
println (s"WHERE $col IN ($valStr)")
case WhereOp(col, op, value) => println (s"WHERE $col $op $value")
case _ => println (s"ERROR: Unknown expression: $where")
}
}
注:本文例子来自programming scala
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: