Is there a way to initialize an object from a prim...
# getting-started
s
Is there a way to initialize an object from a primitive type? Something like
Copy code
data class Foo(val a: String) {
    
    init {
        //magic that takes string and sets it to a
    }
}

var Bar : Foo = "b"
s
No. Generally speaking, Kotlin avoids this kind of implicit behavior
maybe consider an extension function?
Copy code
fun String.asFoo() = Foo(this)

val bar = "b".asFoo()
it’s maybe not as concise as just calling the constructor, but maybe it fits better in your code, stylistically speaking
s
Yeah it makes sense - I’ve seen something analogous in Swift so I was wondering if I was missing out on a language feature thanks for the tip and recommendation 😃
👍 1
s
You also might consider just using a typealias, though that wouldn’t have the same type safety as
ExpressibleByStringLiteral
s
interesting. I’m not seeing how typealias helps here, would you have a quick example?
s
I just mean in the case where you literally only want a better name for your String usage - if your string-containing data class has other functionality, then you’re right that a typealias won’t help
s
aah got it thanks 😁
💯 1