1 /* 2 * The MIT License 3 * 4 * Copyright (c) 2018 Niek Haarman 5 * Copyright (c) 2007 Mockito contributors 6 * 7 * Permission is hereby granted, free of charge, to any person obtaining a copy 8 * of this software and associated documentation files (the "Software"), to deal 9 * in the Software without restriction, including without limitation the rights 10 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 11 * copies of the Software, and to permit persons to whom the Software is 12 * furnished to do so, subject to the following conditions: 13 * 14 * The above copyright notice and this permission notice shall be included in 15 * all copies or substantial portions of the Software. 16 * 17 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 18 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 19 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 20 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 21 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 22 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 23 * THE SOFTWARE. 24 */ 25 26 package org.mockito.kotlin.internal 27 28 import kotlin.reflect.KClass 29 import java.lang.reflect.Array as JavaArray 30 createInstancenull31 inline fun <reified T : Any> createInstance(): T { 32 return when (T::class) { 33 Boolean::class -> false as T 34 Byte::class -> 0.toByte() as T 35 Char::class -> 0.toChar() as T 36 Short::class -> 0.toShort() as T 37 Int::class -> 0 as T 38 Long::class -> 0L as T 39 Float::class -> 0f as T 40 Double::class -> 0.0 as T 41 else -> createInstance(T::class) 42 } 43 } 44 createInstancenull45 fun <T : Any> createInstance(kClass: KClass<T>): T { 46 return castNull() 47 } 48 49 /** 50 * Uses a quirk in the bytecode generated by Kotlin 51 * to cast [null] to a non-null type. 52 * 53 * See https://youtrack.jetbrains.com/issue/KT-8135. 54 */ 55 @Suppress("UNCHECKED_CAST") castNullnull56 private fun <T> castNull(): T = null as T 57