Is it possible to add const to exist class as functions?

#1

so I mean that it is possible to define

fun String.lastCharr():Char = this.get(this.length-1)
val String.LAST_CHAR: String
get()=“Last”

and use like println(“lenas”.lastCharr()) or println(“lenas”.LAST_CHAR)

but is it possible to extend String with new const to use it like
println(String.NEW_CONST)

thanks for any ideas

#2

desision was

MyString.kt

package foo
val String.Companion.MY_LENA_CONST: String
    get() = "Hello, Lena!"

App.kt

import foo.MY_LENA_CONST
class App {
    object App {
        @JvmStatic
        fun main(args: Array<String>) {
            println(String.MY_LENA_CONST)
        }
    }
}
#3

You found the answer to your original question, but a couple of things on this last bit of code:

  • You don’t need to have both a class App and and object App. If all you want is a static container for a function, you can have object App at the top level of your code. This will work even from Java, with the @JvmStatic annotation. You would just call App.main() like you would with any method of a static Java class.
  • Alternately, you could have an anonymous companion object, which also gets called as App.main():
class App {
    companion object {
        fun main()
    }
}
  • Because this is main though, you don’t even need that. You can just do fun main(args: Array<String>) at the top level of your code.
1 Like