Generics
Type Constraints
Require a generic value to provide a known operation.
Type Constraints
TypeConstraints.kt
interface HasCode {
fun code(): String
}
class Product(val prefix: String) : HasCode {
override fun code(): String {
return "$prefix-1"
}
}
fun <T : HasCode> codeLabel(item: T): String {
val code = item.code()
return "code:$code"
}
fun main() {
val prefix =
val product = Product(prefix)
val label = codeLabel(product)
println("prefix=$prefix")
println("label=$label")
}
interface HasCode {
fun code(): String
}
class Product(val prefix: String) : HasCode {
override fun code(): String {
return "$prefix-1"
}
}
fun <T : HasCode> codeLabel(item: T): String {
val code = item.code()
return "code:$code"
}
fun main() {
val prefix =
val product = Product(prefix)
val label = codeLabel(product)
println("prefix=$prefix")
println("label=$label")
}
interface HasCode {
fun code(): String
}
class Product(val prefix: String) : HasCode {
override fun code(): String {
return "$prefix-1"
}
}
fun <T : HasCode> codeLabel(item: T): String {
val code = item.code()
return "code:$code"
}
fun main() {
val prefix =
val product = Product(prefix)
val label = codeLabel(product)
println("prefix=$prefix")
println("label=$label")
}
type-constraint
A type constraint lets generic code call members promised by an interface or superclass.