unnsse
04/07/2022, 1:17 AMunnsse
04/07/2022, 1:18 AMianbrandt
04/07/2022, 1:33 AMunnsse
04/07/2022, 2:26 AMunnsse
04/07/2022, 2:31 AMunnsse
04/07/2022, 2:31 AMianbrandt
05/04/2022, 11:46 PMianbrandt
11/03/2022, 1:01 AMBrendan Campbell-hartzell
02/02/2023, 8:33 PMunnsse
03/02/2023, 2:22 AMianbrandt
03/28/2023, 10:48 PMunnsse
04/06/2023, 1:17 AMDavid Whittaker
04/14/2023, 12:19 AMJack Leow
08/01/2023, 5:23 PMianbrandt
09/07/2023, 1:04 AMianbrandt
10/05/2023, 1:27 AMsdkotlin
10/20/2023, 2:24 AMianbrandt
11/01/2023, 5:38 PMJack Leow
11/02/2023, 3:33 AMJack Leow
11/02/2023, 3:34 AMRene
02/10/2024, 3:00 AMfun <T> otherExecute(input: T){
if (input is String){
println((input as String).length)
}
}
with reified and inline
inline fun <reified T> otherExecute(input: T){
if (T::class == String::class){
println((input as String).length)
}
}
baxter
02/11/2024, 6:22 PMT
and if it's a string, you cast that type as such and print the length.
The second approach is actually not a function (although it is written as one). The inline
keyword basically tells the Kotlin compiler to replace any caller of the otherExecute()
function with the body you provided. So if you have the following snippet:
fun main() {
otherExecute("blah")
}
When compiled to bytecode, it'll essentially be this in Java:
class MainKt {
public static void main(String[] args) {
if (String.class.equals(String.class)) {
System.out.println(((String) "blah").getLength())
}
}
}
Now, the reified
keyword basically tells the compiler that T
shouldn't be treated as a generic, but as the actual class object. That allows you to do reflection or other operations on T
that you couldn't normally do with generics.
This article is a good read on helping understand reified
and `inline`: https://www.baeldung.com/kotlin/reified-functionsRene
03/04/2024, 6:57 PMRene
03/05/2024, 4:44 PMinterface Membership{ fun benefits() }
abstract class FactoryMembership() { abstract fun create() : Membership }
class VipMembership() : Membership { override fun benefits(){ println("your benefits") }}
class VipMembershipFactory : FactoryMembership() { override fun create() = VipMembership() }
client code
val vipFactory : MembershipFactory = VipMembershipFactory()
val vipMembership : Membership = vipFactory.create()
ianbrandt
03/27/2024, 2:44 AMunnsse
04/04/2024, 3:36 AMianbrandt
11/20/2024, 4:01 AMunnsse
03/26/2025, 4:57 AMunnsse
03/26/2025, 5:07 AMunnsse
04/09/2025, 7:22 PM