Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/powerbi/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Syntax 科特林二级建造师_Syntax_Constructor_Kotlin - Fatal编程技术网

Syntax 科特林二级建造师

Syntax 科特林二级建造师,syntax,constructor,kotlin,Syntax,Constructor,Kotlin,如何在Kotlin中声明二级构造函数 有关于这方面的文件吗 以下内容不编译 class C(a : Int) { // Secondary constructor this(s : String) : this(s.length) { ... } } 更新:自M11(0.11.*)以来,Kotlin支持 目前,Kotlin只支持主构造函数(稍后可能支持辅助构造函数) 二级构造函数的大多数用例通过以下技术之一解决: 技巧1。(解决您的问题)在类旁边定义工厂方法 fun C(s: Str

如何在Kotlin中声明二级构造函数

有关于这方面的文件吗

以下内容不编译

class C(a : Int) {
  // Secondary constructor
  this(s : String) : this(s.length) { ... }
}

更新:自M11(0.11.*)以来,Kotlin支持


目前,Kotlin只支持主构造函数(稍后可能支持辅助构造函数)

二级构造函数的大多数用例通过以下技术之一解决:

技巧1。(解决您的问题)在类旁边定义工厂方法

fun C(s: String) = C(s.length)
class C(a: Int) { ... }
用法:

val c1 = C(1) // constructor
val c2 = C("str") // factory method
val c1 = C("foo") // parameter passed explicitly
val c2 = C() // default value used
val c = C.new("foo")
技术2.(也可能有用)定义参数的默认值

class C(name: String? = null) {...}
用法:

val c1 = C(1) // constructor
val c2 = C("str") // factory method
val c1 = C("foo") // parameter passed explicitly
val c2 = C() // default value used
val c = C.new("foo")
请注意,默认值适用于任何函数,而不仅仅适用于构造函数

技术3。(当需要封装时)使用在伴随对象中定义的工厂方法

有时,您希望构造函数是私有的,并且客户端只能使用工厂方法。目前,这仅适用于伴生对象中定义的工厂方法:

class C private (s: Int) {
    companion object {
        fun new(s: String) = C(s.length)
    }
}
用法:

val c1 = C(1) // constructor
val c2 = C("str") // factory method
val c1 = C("foo") // parameter passed explicitly
val c2 = C() // default value used
val c = C.new("foo")

我刚刚看到这个问题,我想可能还有另一种技术,听起来比安德烈提出的技术更好

class C(a: Int) {
    class object {
        fun invoke(name: String) = C(name.length)
    }        
}
您可以编写类似于
val c:c=c(3)
val c:c=c(“abc”)
的代码,因为
调用
方法的工作方式与
应用
方法在Scala中的工作方式相同

更新

到目前为止,二级构造函数已经是语言规范的一部分,因此不应使用此解决方法。

作为一个实例,您可以这样使用二级构造函数

class GoogleMapsRestApiClient constructor(val baseUrl: String) {

    constructor() : this("https://api.whatever.com/")

}
请记住,必须扩展第一个构造函数行为

class Person(val name: String) {
    constructor(name: String, parent: Person) : this(name) {
        parent.children.add(this)
    }
}

您可以试试这个。

下面的代码片段应该可以工作

class  C(a:Int){
  constructor(s:String):this(s.length){..}
}

要声明次要构造函数,只需使用构造函数关键字:like

这是一个主构造函数:

class Person constructor(firstName: String) {

}

对于这样的二级构造函数代码:

class Person(val name: String) {
    constructor(name: String, parent: Person) : this(name) {
        parent.children.add(this)
    }
}
data class MyClass(val a: Int? = null, val b: String? = null, val c: Double? = null)
必须调用主构造函数,否则编译器将抛出以下错误

Primary constructor call expected

kotlin二级构造函数示例

class Person(name: String){
    var name=""
    var age=0

    constructor(age :Int,name : String)  : this(name){
        this.age=age
        this.name=name
    }
    fun display(){
        print("Kotlin Secondary constructor $name  , $age")
    }
}
主要功能

fun main(args : Array<String>){

    var objd=Person(25,"Deven")
    objd.display()
}
fun main(args:Array){
var objd=个人(25,“德文”)
objd.display()
}

您可以使用
构造函数在Kotlin中定义多个构造函数,但需要跳过默认构造函数
类AuthLog(\u data:String)

更新

现在可以定义默认构造函数了

class AuthLog(_data: String, _numberOfData: Int) {

    constructor(_data: String): this(_data, -1) {
        //TODO: Add some code here if you want
    }

    constructor(_numberOfData: Int): this("From count", _numberOfData)

}

具有
init
的构造函数:

class PhoneWatcher : TextWatcher {

    private val editText: EditText
    private val mask: String

    private var variable1: Boolean = false
    private var variable2: Boolean = false

    init {
        variable1 = false
        variable2 = false
    }

    constructor(editText: EditText) : this(editText, "##-###-###-####")

    constructor(editText: EditText, mask: String) {
        this.editText = editText
        this.mask = mask
    }
    ...
}

我对大多数答案都有点困惑。 为了便于理解,我添加了一个包含更多元素的示例:

   @JsonInclude(JsonInclude.Include.NON_NULL)
   data class Response(val code: String) {
      var description: String? = null
      var value: String? = null

      constructor(code: String, description: String?) : this(code) {
          this.description = description
      }

      constructor(code: String, description: String?, value: String) : this(code, description) {
          this.value = value
      }
   }

来不及回答,但以下是我微薄的贡献:)

由于Kotlin支持默认参数值,(注意:我想使用null的幂),如下所示:

class Person(val name: String) {
    constructor(name: String, parent: Person) : this(name) {
        parent.children.add(this)
    }
}
data class MyClass(val a: Int? = null, val b: String? = null, val c: Double? = null)
我们不需要有多个构造函数。但即使我们想要,我们也可以这样做:

data class MyClass(val a: Int?, val b: String?, val c: Double?){
    constructor() : this(null,null,null)
    constructor(a : Int) : this(a,null,null)
    constructor(a : Int, b: String) : this(a,b,null)
}
我们可以通过以下方式实例化此类:

println(MyClass().toString())
println(MyClass(1).toString())
println(MyClass(1,"String").toString())
println(MyClass(1,"String",0.5).toString())
让我们也来看看结果:


Android中具有多个构造函数的自定义视图示例:

class ShaderBackground : View {


    constructor(context: Context) : super(context) {
        init()
    }

    constructor(context: Context, attrs: AttributeSet) : super(context, attrs) {
        init()
    }

    constructor(context: Context, attrs: AttributeSet, defStyleAttr: Int) : super(
        context,
        attrs,
        defStyleAttr
    ) {
        init()
    }

    private fun init() {

       // Init stuff here
        paint = Paint();
        paint.strokeWidth = 10f;
        paint.style = Paint.Style.FILL_AND_STROKE;

    }

使用变量“internal”,然后可以在单个类中添加多个构造函数,如下所示。这将完美地工作

class AuthModel {
var code: String? = null

internal constructor(code: String?) {
    this.code = code
}

internal constructor() {}
}

如果从不支持辅助构造函数,则应重命名主构造函数。;)Andrey Breslav,我认为在Kotlin中放弃对二级构造函数的支持是个坏主意,因为这些构造函数有时是必要的,尤其是在使用Java框架和扩展Java类时。希望你能很快把它们拿回来。这很有趣:二级构造函数返回:)二级构造函数是在M11中添加的。是否仍然认为使用有效Java中描述的静态工厂方法是最佳实践?还是现在没有必要?我想如果你预见到控制实例的需要,你会一直想使用静态工厂。二级构造函数(因为M11)比这个选项好。我在M11发布之前回答了这个问题,否决它是相当刻薄的,你为什么不试着编辑答案呢?我无法编辑答案,因为我的编辑与你的答案不一致。我完全不同意这种说法。删除你的答案会阻止我投反对票。也许这在M11之前是一个有用的黑客攻击,但现在不是,也不应该出现在这里。如果你离开它,你会邀请新的反对票。保持你的旧帖子更新,你就不会遇到这种情况。不是直接从第二个构造函数扩展第一个构造函数,而是可以委托给另一个二级构造函数,后者已经这样做了:我认为这一个更适合当前情况:`class GoogleMapsRestApiClient构造函数(val baseUrl:String=“){//class body}‘是的!但这不是问题的背景^^如果你有更好的建议,我可以用更好的建议来edi它。谢谢你大喊@AlexanderKrolAny为korlin文件创建构造函数的快捷方式。我尝试了ALT+INSERT,但没有显示任何生成构造函数的菜单。你能分享为kotlin POJ生成构造函数的快捷方式吗哦?