sievy
sievy

Reputation: 67

Semantic operator of dot in Kotlin

I'd like to understand a bit better the 2 functions below. I know it is very compact and understand more or less what it does: it converts each characters of a string into string of '0' and '1'. But... How does the dot(in front of encodeToByteArray) connect the 's' to encodeToByteArray()? Where can I find more info about what dot represents? Also, how and why the code { byte -> binaryStringOf(byte) } can do the job in that place? How does it "know" that there is a byte with which it calls the function binaryStringOf(byte) Where can I find more info about it, too?

fun binaryStringOf(message: String): String {
    var s: String
    s = (message)
        .encodeToByteArray()
        .joinToString("") { byte -> binaryStringOf(byte) }
        return s
    }
fun binaryStringOf(b: Byte): String {
    return b.toString(2).padStart(8, '0')
}

Upvotes: 0

Views: 196

Answers (2)

kagof
kagof

Reputation: 553

The formatting above makes things a little bit more confusing, but let me try to explain what is going on.

The = is an assignment operator. It says "assign the variable s to the result of the expression on the right side".

Now we see that message is a parameter in the binaryStringOf function of type String. String is a class which contains a function (also called a method when it is a member of a class) called encodeToByteArray which returns a ByteArray.

ByteArray in turn has a function called joinToString which we're giving two parameters: one of type String, and one of type ((Byte) -> CharSequence) (ie, the function is itself being passed in as a variable, using lambda syntax). Kotlin has some syntactic sugar to make this look nicer when the lambda is the last argument.

So, the statement

    s = (message)
        .encodeToByteArray()
        .joinToString("") { byte -> binaryStringOf(byte) }

means "the variable s is assigned the value that results from calling joinToString on the result of calling encodeToByteArray on message.

Then return s says that the return value from the binaryStringOf should be whatever value was assigned to s.

Upvotes: 1

GhostCat
GhostCat

Reputation: 140447

.encodeToByteArray()

works on the incoming string (message in this case). It returns a ByteArray; so something that represents an array of Byte values.

And on that array object, it invokes the joinToString() method. That method receives various arguments, but only the separator string ("") is provided, and the transform parameter.

Now: transform is a function. It is something that can be invoked, with parameters, and that has to return a specific result.

The key part to understand is that { byte -> ... } is that transform function parameter.

Upvotes: -1

Related Questions