如何在Kotlin中创建可作用于所有数据类型的printDatatype扩展函数?
Hey there! Let's build that printDatatype extension function you're after—Kotlin's extension functions make this super straightforward, since we can add this behavior to every possible type, including null and custom classes. Here's a complete implementation that matches your requirements:
printDatatype Extension Function The Core Function
We'll define the extension on Any? so it's available for literally every type (nullable included). We'll handle different cases with a when block to match your expected output:
import kotlin.reflect.full.memberProperties fun Any?.printDatatype() { when (this) { // Handle null explicitly to output "null" null -> println("null") // For strings, print the raw value directly is String -> println(this) // Cover all number types (Int, Double, Float, Long, etc.) is Number -> println(this) // For custom classes, print class name + properties and their values else -> { val className = this::class.simpleName ?: "UnnamedClass" // Use reflection to fetch all properties and format their key-value pairs val propertyDetails = this::class.memberProperties .map { prop -> "${prop.name} = ${prop.get(this)}" } .joinToString(", ") println("$className($propertyDetails)") } } }
Test It With Your Examples
Let's validate each scenario you mentioned:
String input:
"example".printDatatype() // Output: exampleNumber input:
56.printDatatype() // Output: 56Null input:
null.printDatatype() // Output: nullCustom class input:
First, define a sample class (works for both data classes and regular classes):class User(val username: String, val email: String, val age: Int)Then use the function:
val newUser = User("johndoe", "john@example.com", 28) newUser.printDatatype() // Output: User(username = johndoe, email = john@example.com, age = 28)
Quick Notes
- Reflection Dependency: The custom class property printing uses Kotlin reflection, so you'll need to add the
kotlin-reflectdependency to your project. For Gradle, add this line to yourbuild.gradle.kts:implementation("org.jetbrains.kotlin:kotlin-reflect:1.9.20") - Customization: If you want to handle other primitives (like
BooleanorChar) explicitly, just add anotheris Typecheck in thewhenblock. - Data Classes: Data classes already have a built-in
toString()that outputs similar content, but this function works seamlessly for non-data classes too—no need to overridetoString()for every class you create.
内容的提问来源于stack exchange,提问作者Omar Younis

