当前位置:网站首页>Kotlin apply method

Kotlin apply method

2022-06-11 02:29:00 ScottePerk

apply Method can merge multiple steps . Some configurations can be made in advance . Very easy to use .
For example, the following code , Code 1 implements the configuration of a read-only file in the traditional way , Code 2 encapsulates this code into apply Inside , Compared with the first , The advantage is that the code set , The structure is clear .

Here are a few points to explain .
1.apply Will be able to this Pass in lambda expression , That is to say {} Inside , Code one file Variable .
2.apply return file Oneself .

fun main() {
    

    // Code 1 
    var file = File("test.txt");
    file.setExecutable(true)
    file.setReadable(true)
    file.setWritable(false)
    
    // Code 2 
    var readOnlyfile = file.apply() {
    
        setExecutable(true)
        setReadable(true)
        setWritable(false)
    }

    readOnlyfile.mkdir();
}
原网站

版权声明
本文为[ScottePerk]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/162/202206110126250506.html