【Scala之旅】参数与操作符
默认参数Scala提供了给参数默认值的能力,可以让调用者忽略这些参数。 def log(message: String,level: String = "INFO") = println(s"$level: $message") log("System starting") // prints INFO: System starting log("User not found","WARNING") // prints WARNING: User not found 参数 class Point(val x: Double = 0,val y: Double = 0) val point1 = new Point(y = 1) 这里我们必须要指明 注意,当从 Java 代码调用时,Scala中的默认参数不是可选的: // Point.scala class Point(val x: Double = 0,val y: Double = 0) // Main.java public class Main { public static void main(String[] args) { Point point = new Point(1); // does not compile } } 带名参数在调用方法时,您可以使用参数名称来标记参数: def printName(first: String,last: String): Unit = { println(first + " " + last) } printName("John","Smith") // Prints "John Smith" printName(first = "John",last = "Smith") // Prints "John Smith" printName(last = "Smith",first = "John") // Prints "John Smith" 注意命名参数的顺序可以重新排列。但是,如果有一些参数被命名,而另一些参数没有,则未命名的参数必须以方法签名中参数的顺序排在第一位。 def printName(first: String,last: String): Unit = { println(first + " " + last) } printName(last = "Smith","john") // Does not compile 请注意,带名参数与对Java方法的调用不兼容。 操作符在 Scala 中,操作符是一个方法。任何带有单个参数的方法都可以使用中缀操作符。例如, 10.+(1) 然而,作为一个中缀操作符更容易阅读: 10 + 1 定义和使用操作符你可以使用任何合法的标识符作为操作符。这包括 case class Vec(val x: Double,val y: Double) { def +(that: Vec) = new Vec(this.x + that.x,this.y + that.y) } val vector1 = Vec(1.0,1.0) val vector2 = Vec(2.0,2.0) val vector3 = vector1 + vector2 vector3.x // 3.0 vector3.y // 3.0 类 case class MyBool(x: Boolean) { def and(that: MyBool): MyBool = if (x) that else this def or(that: MyBool): MyBool = if (x) this else that def negate: MyBool = MyBool(!x) } 现在可以使用将 def not(x: MyBool) = x.negate def xor(x: MyBool,y: MyBool) = (x or y) and not(x and y) 这有助于使 优先级当一个表达式使用多个操作符时,操作符会根据第一个字符的优先级进行计算。 (characters not shown below) * / % + - : = ! < > & ^ | (all letters) 这适用于你定义的函数。例如,下面的表达式: a + b ^? c ?^ d less a ==> b | c 相似于 ((a + b) ^? (c ?^ d)) less ((a ==> b) | c)
提取器对象提取器对象是具有一个 import scala.util.Random object CustomerID { def apply(name: String) = s"$name--${Random.nextLong}" def unapply(customerID: String): Option[String] = { val name = customerID.split("--").head if (name.nonEmpty) Some(name) else None } } val customer1ID = CustomerID("Sukyoung") // Sukyoung--23098234908 customer1ID match { case CustomerID(name) => println(name) // prints Sukyoung case _ => println("Could not extract a CustomerID") }
val customer2ID = CustomerID("Nico") val CustomerID(name) = customer2ID println(name) // prints Nico 这相当于 val CustomerID(name2) = "--asdfasdfasdf"
有时,子值的数量不是固定的,我们希望返回一个序列。出于这个原因,你还可以通过 (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |