版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/u011707542/article/details/78649348
/**
* Created by hhy on 2017/11/27.
*/
/**
* 函数式对象之先决条件
* 在面向对象编程中,为了确保数据在整个程序生命周期内的有效性,一般会将数据封装到对象内,而对于函数式对象是不具有改变任何状态的类,
* 例如不可变的对象就需要保证对象在创建时数据的有效性,此时会用到先决条件,使用先决条件的格式如下所示。
* final def require(requirement:Boolean,message:=>Any):Unit
* 其中require是限制条件,布尔类型返回false或者true message是不满足条件时候的错误信息,可以是任意类型,require返回类型为Unit
* 先决条件时对传递给方法或者构造器的值进行的限制,也就是说调用者必须满足这一条件,才能正确的调用。
* */
class Person(head:Int,hand:Int,foot:Int,name:String){
//先决条件 boolean类型
require(head>0&&head<2,"error input of hand,please input hand retring")
//当传入的值不满足时候程序运行异常,异常信息为“error input...”
require(foot>=0&&foot<3,foot)
//定义Working方法
def Working(fangFa:String)={
val total=head+hand+foot
println(name+"is a"+fangFa+" and working by \n\t" +head+" head to think and " +
"\n\t"+hand+"handsto cooperate something and \n\t"+ foot+"foots to walk!")
println(name+"are use total Organ:"+total)
total
}
//在伴生对象中调用
object FunctionObject{
def main(args:Array[String]):Unit={
val people=new Person(1,2,2,"Tom")
people.Working("Programmmer")
}
}
/**
* 函数式对象之自指向
* This关键字指向当前执行方法被调用的对象实例,或者如果使用构造器的话,就是正被构建的对象实例
* 在下面定义的方法 < 中传入了一个SubConstructor类型的参数,其中this.A this.B中的this是指调用方法的对象实例,
* this可以省略;但是方法selfDiction中第一个this可以省略 但是第二天this不可以省略了
* */
class SubConstructor(n:Int,m:Int){
require(m!=0)
def this(a:Int)=this(a,10)
def compare(a:Int,b:Int)=if(b==0)a%b else a
val X=compare(n,m)
def A=n*X
def B=m*X
//定义方法<
def <(that:SubConstructor)=this.A*that.B<that.A*this.B
def selfDiction(that:SubConstructor):SubConstructor=if(this.<(that))that else this
}
//单例对象
object SubConstructor{
def main(args: Array[String]): Unit = {
val subAdd=new SubConstructor(4,6)
val add=subAdd.compare(7,5)
print(add)
println(subAdd.X)
}
}
/**
* 函数式对象之辅助构造器
*在定义类的时候“()”后面的内容会被定义为主构造器,那就是主构造器与类定义混合在一起,
* 在一个类中,如果没有明确定义主构造器的话,则默认构造一个无参数的主构造器。
* 辅助构造器扩充了主构造器的内容,在Java中构造器的名称和类名保持一致,但Scala中是以this为名称的,并且定义开始于def this(...)
* 在scala中,可以有若干个辅助构造器,当一个辅助构造器在执行的时候会首先调用相同类下的其他构造器,可以是主构造器也可以是
* 已经创建的其他辅助构造器,而辅助构造器的调用起始于是主构造器的调用的结束
* */
class constructorAnx{
private var name=""
private var age=0
//定义辅助构造器
def this(name:String){
//调用主构造器
this()
this.name=name
println(name)
}
//定义另一个辅助构造器
def this(name:String,age:Int){
//调用前一个辅助构造器
this(name)
this.name=name
this.age=age
println(name+" , "+age)
}
}
//伴生对象
object constructorAnx{
def main(args: Array[String]): Unit = {
//主构造器
val bigDate=new constructorAnx
//辅助构造器
val hadoop=new constructorAnx("Hadoop")
val spark=new constructorAnx("Spark",4)
}
}
/**
* 函数式对象之scala标识符
* Scala的标识符包含了字母、数字、下划线、首字符为字母或者下划线,scala命名遵循驼峰式的习惯,如HashMap、SparkContext
* 需要注意的是“_”虽然是合法的,但是“_”还有其他用途 以免冲突
* Scala与Java区别是常量名,Java中常量名都是大写 但是Scala中只是首字母大写
* 操作标识符由若干个操作字符组成,通常是一些七位可打印的ASCII字符,这些字符不包括字母 括号 数字 下划线以及回退字符等,
* 操作标识符也可以属于数学符号或者其他符号的Unicode集,例如+,-, ->,<>等。
* */
}