[7] Extended function attributes for Kotlin learning

extension function

  • Create a new kt file BaseString
  • new method
fun String.lastChar() = this[length - 1]
  • Code call display results
fun main() {
    println("Test".lastChar())
}

result

t

According to this, we can define the effect we want
, such as:

package strings

fun String.lastChar() = this[length - 1]

fun String.lastCharUpper() = this.substring(0,length-1)+lastChar().toUpperCase()

code call

fun main() {
    println("Test".lastChar())
    println("Test".lastCharUpper())
}

result

t
TesT

extended attributes

Declare extension properties of StringBuilder

var StringBuilder.firstChar: Char
    get() = this[0]
    set(value) {
        setCharAt(0, value)
    }

code call

fun main() {
    var s = StringBuilder("Test")
    println(s.firstChar)
    s.firstChar = 'B'
    println(s)
}

result

T
Best

Guess you like

Origin blog.csdn.net/a940659387/article/details/116047403
Recommended