Kotlin - 了解吸气剂和二传手

时间:2016-11-05 13:04:30

标签: kotlin

Kotlin自动生成它的吸气剂和设置,但我从不参考它们?另外,在Kotlin中编写自定义getter / setter的正确方法是什么?当我说public class ClientThread extends Thread{ public Socket socket; BufferedReader in; PrintWriter out; public ClientThread(Socket socket) throws IOException{ this.socket = socket; Status.stausChanged("New client connected..."); //status TextArea } @Override public void run () { try{ out = new PrintWriter(socket.getOutputStream()); in = new BufferedReader (new InputStreamReader (socket.getInputStream())); String msg ; try { msg = in.readLine(); Graphic.enterIP.setText(socket.getInetAddress().getHostAddress()); //show IP in separate window //recieving message while(msg!=null){ msg = in.readLine(); Status.stausChanged("Client ".concat(socket.getInetAddress().getHostAddress().concat(": ").concat(msg))); } out.close(); socket.close(); } catch (IOException e) { } } catch(IOException exc){System.out.println("An error occured: " + exc.getMessage());} } } 时,我觉得myObj.myVar = 99myVar的公共字段,我直接访问该字段?这里到底发生了什么?

2 个答案:

答案 0 :(得分:19)

在一些地方已经回答了这个问题,但我想我会分享一个具体的例子,让人们从Java / C#/ C / C ++过渡到Kotlin,并且我有同样的问题:

我很难理解getter和setter在Kotlin中是如何工作的,特别是因为它们从未被明确调用过(因为它们在Java中)。因此,我感到不舒服,因为我们只是直接将vars / vals称为字段。所以我做了一个小实验来证明事实并非如此,事实上它是隐藏的(自动生成的)或显式的getter / setter,当你访问变量/值时在Kotlin中调用它。不同的是,您没有明确要求默认的getter / setter。

documentation - 声明属性的完整语法是:

var <propertyName>: <PropertyType> [= <property_initializer>]
   [<getter>]
   [<setter>]

我的例子是

class modifiersEg {

/** this will not compile unless:
 *      - we assign a default here
 *      - init it in the (or all, if multiple) constructor
 *      - insert the lateinit keyword    */
var someNum: Int?
var someStr0: String = "hello"
var someStr1: String = "hello"
    get() = field  // field is actually this.someStr1, and 'this' is your class/obj instance
    set(value) { field = value }

// kotlin actually creates the same setters and getters for someStr0
// as we explicitly created for someStr1

var someStr2: String? = "inital val"
    set(value) { field = "ignore you" }

var someStr3: String = "inital val"
    get() = "you'll never know what this var actually contains"

init {
    someNum = 0

    println(someStr2) // should print "inital val"

    someStr2 = "blah blah blah"
    println(someStr2) // should print "ignore you"

    println(someStr3) // should print "you'll never know what this var actually contains"
}

我希望这对其他人有帮助吗?

答案 1 :(得分:0)

以下是一些自定义获取器和设置器的真实示例。 You can see more here

[ { key1: value1 }, { key2: value2 } ]