I made this extension function for operator "*" ``...
# random
a
I made this extension function for operator "*"
Copy code
operator fun String.times(i: Int){
      var string: String? = null
       repeat(i){
            string = this
       }
       return string
}
Copy code
fun main(){
       print("hello"*8)
}
It suppose to print 8x but it returns null from the fun or print only 1 hello
c
how it is supposed to know the the symbol “*” should trigger this “times”?
w
I think you need
string += this
and not
string = this
☝️ 1
r
Copy code
operator fun String.times(i: Int): String {
    var string = ""
    repeat(i){
        string += this
    }
    return string
}
m
a
Oh, thanks all for help I never thought t"+" would have that much effect
m
Copy code
operator fun String?.times(i: Int) = this?.repeat(i)
🔥 2
a
@Cicero there is operator in the function
c
Danke 🙂
😉 1
r
@Mikael Alfredsson I’d suggest not making the receiver type nullable; it means that
"hello" * 1
has type
String?
, which I’d find more of a pain than occasionally having to do
val x: String? = null; x?.times(1)
m
@Rob Elliot You’re right. it was an optimization to far 🙂
so the corrected version for @Ananiya
Copy code
operator fun String.times(i: Int) = this.repeat(i)
and the compiler will tell you if you are trying to call it on a nullable string
🤩 1
a
Thanks @Mikael Alfredsson, I can do that with also if else to make that more secure
c
This was a very cool short class
l
Why not use the
repeat
extension for
String
?
a
Yeah , you are right but that would be realy easy for my project only one symbol
l
Your project cannot afford to have
repeat
typed? blob thinking upside down
I'm wondering what makes it so, not saying it's a bad idea to use the times operator since the behavior you're looking for is quite natural regarding its name and its symbol (
*
).
a
no 🤣 🤣, just to decrease lines. dont take that seriosly