Kotlin:在界面中指定输入约束 [英] Kotlin: Specify input-constraints in interface

查看:101
本文介绍了Kotlin:在界面中指定输入约束的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

让我们说我有以下接口:

Lets say I have the following interface:

interface MathThing {

    fun mathFunction(x : Int)
}

假设我要对此函数施加的约束是x不能为负。

Let's say the constraint I want to put onto this function is that x cannot be negative.

如何确保每次在MathThing类型的对象上都不满足此(或任何其他任意)条件时,

How can I make sure that every time this (or any other arbitrary) condition isn't met on a object of type MathThing, a (custom) exception is thrown?

推荐答案

一种方法是对函数参数使用包装器类。您可以创建扩展函数,以便将值传递给该函数更容易一些。

One way is to use a wrapper class for your function parameters. You can make an extension function so it's a little easier to pass values to the function.

data class NonNegative(val value: Int) {
    init{ if (value < 0) throw IllegalArgumentException("Input must not be negative.") }
}

fun Int.nonNegative() = NonNegative(this)

interface MathThing {
    fun mathFunction(x : NonNegative)
}

这篇关于Kotlin:在界面中指定输入约束的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆