Scala辅助构造函数
发布时间:2020-12-16 09:10:12 所属栏目:安全 来源:网络整理
导读:以下是带有助理员的 Scala课程.我的问题标有** class Constructors( a:Int,b:Int ) {def this() = { this(4,5) val s : String = "I want to dance after calling constuructor" //**** Constuctors does not take parameters error? What is this compile e
以下是带有助理员的
Scala课程.我的问题标有**
class Constructors( a:Int,b:Int ) { def this() = { this(4,5) val s : String = "I want to dance after calling constuructor" //**** Constuctors does not take parameters error? What is this compile error? this(4,5) } def this(a:Int,b:Int,c:Int) = { //called constructor's definition must precede calling constructor's definition this(5) } def this(d:Int) // **** no equal to works? def this(d:Int) = //that means you can have a constructor procedure and not a function { this() } //A private constructor private def this(a:String) = this(1) //**** What does this mean? private[this] def this(a:Boolean) = this("true") //Constuctors does not return anything,not even Unit (read void) def this(a:Double):Unit = this(10,20,30) } 你可以在上面的**中回答我的问题吗?例如Constuctors没有参数错误?这是什么编译错误? 解决方法
答案1:
scala> class Boo(a: Int) { | def this() = { this(3); println("lol"); this(3) } | def apply(n: Int) = { println("apply with " + n) } | } defined class Boo scala> new Boo() lol apply with 3 res0: Boo = Boo@fdd15b 首先,这个(3)是一个代表主要的构造函数.第二个(3)调用此对象的apply方法,即扩展为this.apply(3).观察上面的例子. 答案2: =在构造函数定义中是可选的,因为它们没有真正返回任何东西.它们与常规方法具有不同的语义. 答3: private [this]被称为对象 – 私有访问修饰符.一个对象不能访问其他对象的私有[this]字段,即使它们都属于同一个类.因此,它比私人更严格.观察下面的错误: scala> class Boo(private val a: Int,private[this] val b: Int) { | def foo() { | println((this.a,this.b)) | } | } defined class Boo scala> new Boo(2,3).foo() (2,3) scala> class Boo(private val a: Int,private[this] val b: Int) { | def foo(that: Boo) { | println((this.a,this.b)) | println((that.a,that.b)) | } | } <console>:17: error: value b is not a member of Boo println((that.a,that.b)) ^ 答案4: 与Ans 2相同. (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |
相关内容
- angularjs – 具有日期和ng-repeat的Angular-xeditable可编
- Scala特征与C概念之间的区别
- Webservice
- webservice客户端异常( undefinedelement declaration '
- bash – 如何去每个目录并执行命令?
- Docker:如何使用ssh访问私有github仓库?
- $watch How the $apply Runs a $digest
- docker-compose v3:使用顶级卷语法在多个容器之间共享装入
- angular – 如何在离开Ionic 3中的Tab之前显示确认消息
- scala – 使用scopt OptionParser和Spark时的NoClassDefFou