本文介绍了在Kotlin中的Setter重载的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当试图定义一个可以接受可用于构造属性的参数类型的setter时,

When trying to define a setter that accepts a parameter type that can be used to construct a property, thusly:

class Buffer(buf: String) {}

class Foo {
    var buffer: Buffer? = null
        set(value: String) {
            field = Buffer(value)
        }
}

我收到错误消息:

那么Kotlin做到这一点意味着什么?

So what's meant to be the Kotlin way of doing this?

推荐答案

从Kotlin 1.1开始,无法重载属性设置器.在此处跟踪功能请求:

As of Kotlin 1.1 it is not possible to overload property setters. The feature request is tracked here:

https://youtrack.jetbrains.com/issue/KT-4075

当前,您必须在String上定义buffer扩展功能:

Currently, you would have to define a buffer extension function on String:

val String.buffer : Buffer
    get() = Buffer(this) 

并使用

Foo().buffer = "123".buffer

这篇关于在Kotlin中的Setter重载的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-31 20:11