You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在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:

Implementing 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:

  1. String input:

    "example".printDatatype() // Output: example
    
  2. Number input:

    56.printDatatype() // Output: 56
    
  3. Null input:

    null.printDatatype() // Output: null
    
  4. Custom 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-reflect dependency to your project. For Gradle, add this line to your build.gradle.kts:
    implementation("org.jetbrains.kotlin:kotlin-reflect:1.9.20")
    
  • Customization: If you want to handle other primitives (like Boolean or Char) explicitly, just add another is Type check in the when block.
  • 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 override toString() for every class you create.

内容的提问来源于stack exchange,提问作者Omar Younis

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.29 10:52:38