https://kotlinlang.org logo
#announcements
Title
# announcements
h

Hullaballoonatic

11/20/2019, 6:35 PM
How can I be sure that casting is safe? Would the following be a completely safe cast, and thus not require a conversion function?
Copy code
class Foo(vararg values: Int) : List<Int> by values.toList() {
    fun bar() = "foobar"
}

(listOf(1, 2, 3) as Foo).bar()
Casting is cheaper than conversion, because it doesn't require instantiating a new object, right?
m

Marko Mitic

11/20/2019, 6:38 PM
It's cheaper but that cast wouldn't work, result of listOf() can never be cast to your custom implementation of List
you can cast it to List, and have
bar
as extension method
You don't even have to cast to List 🙂
4 Views