H5W3
当前位置:H5W3 > 其他技术问题 > 正文

麻烦帮看下scala中两小段代码的含义

有两个问题:
1. val RichFile(a @ _*) = “/home/cay/readme.txt”中,括号中的a @ _*的字符含义
是什么?这是什么语法?
其对应的整个代码如下:

object quick1110_1 extends App {
object RichFile {
def unapplySeq(s: String): Option[Seq[String]] = Some(s.split("/").filter(_!=""))
}
val RichFile(a @ _*) = "/home/cay/readme.txt"
println(a)
}
  1. val (d, c) = (this.toCent() – other.toCent()) /% 100这段代码的含义?(d,c)是元组吗?/%是什么运算符或者什么语法?麻烦解释下这段代码,所在的
    整个代码如下:

object quick1104_2 extends App {
class Money(val dollar: BigInt, val cent: BigInt) {
def +(other: Money): Money = {
val (a, b) = (this.cent + other.cent) /% 100
new Money(this.dollar + other.dollar + a, b)
}
def -(other: Money): Money = {
val (d, c) = (this.toCent() - other.toCent()) /% 100
new Money(d, c)
}
private def toCent() = {
this.dollar * 100 + this.cent
}
def ==(other: Money): Boolean = this.dollar == other.dollar && this.cent == other.cent
def <(other: Money): Boolean = this.dollar < other.dollar || (this.dollar == other.dollar && this.cent < other.cent)
override def toString = "dollar = " + dollar + " cent = " + cent
}
object Money {
def apply(dollar: Int, cent: Int): Money = {
new Money(dollar, cent)
}
}
val m1 = Money(1, 200)
val m2 = Money(2, 2)
println(m1 + m2)
println(m1 - m2)
println(m1 == m2)
println(m1 < m2)
println(Money(1, 75) + Money(0, 50))
println(Money(1, 75) + Money(0, 50) == Money(2, 25))
println(Money(4,2)-Money(2,3))
}

回答

@符号在scala编译中做了一个模式配置的工作,将字符串做了比对,如果值相等,将将这个值取到赋值给变量;如果值不相等,匹配不上,就报一个异常

%是除法取余数
val (d, c) = (this.toCent() - other.toCent()) /% 100
相当于
d = (this.toCent() - other.toCent()) / 100
c = (this.toCent() - other.toCent()) % 100

本文地址:H5W3 » 麻烦帮看下scala中两小段代码的含义

评论 0

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址