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

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

2R <: { 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)符号: =>名字作为一个参数

2R <: { 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


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值