1
val k = " asdfasdf "
fun test() {
    if(k is String) {
     // Do something
    }
}

So, how do I pass that String through the function calls eg:

fun test(xxxx) {
    if(k is xxxx) {
    // do something
    }
}

4 Answers 4

2

Like this:

inline fun <reified T> testType(k: Any) {
   if(k is T) {
     println("is a ${T::class.simpleName}")
   } else {
     println("is not a ${T::class.simpleName}")
   }
}

Call it like this:

test<String>("Hello") // is a String
test<String>(1) // is no String

Here some further reading.

Sign up to request clarification or add additional context in comments.

Comments

2

There are two possibilities, depending on your needs.

1. Use inline and a reified type parameter

You can use the reified keyword on the type parameter in combination with an inline function:

inline fun <reified T> test(k: Any) {
    if (k is T) {
        println("k is a T!")
    }
}

See the documentation on reified.

2. Use KClass<T>

If you do not want to or cannot make your function inline you can use a KClass parameter:

fun <T : Any> test(k: Any, type: KClass<T>) {
    if (type.isInstance(k)) {
        println("k is a T!")
    }
}

Comments

2

You can either use a predicate, e.g.:

fun testIt(predicate: (Any?) -> Boolean) {
  if (predicate(k)) {
    println("matches!")
  } else println("nope")
}

and call it as follows:

testIt { it is String }
testIt { it is Int }

Or you can use a reified type:

inline fun <reified T> testIt() {
  when (k) {
    is T -> println("matches!")
    else -> println("nope")
  }
}

and call it like:

testIt<String>()
testIt<Int>()

For simplicity I kept your current variable inside the testIt-method... you may want to redesign that ;-)

I basically assumed a member variable as follows: var k : Any? = null

Comments

1
inline fun <reified T> isType(obj: Any): Boolean {
    return obj is T
}

fun main(args: Array<String>) {
    val test = "This is a String"
    if (isType<String>(test)) {
        println("Success")
    } else {
        println("Failure")
    }
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.