1. 程式人生 > >Interfaces in Kotlin. Who said interfaces can't have code?

Interfaces in Kotlin. Who said interfaces can't have code?

The interfaces in Kotlin will allow you to reuse more code than what you can get with Java.

The reason is very simple: you can add code to your interfaces. If you’ve tried Java 8, it’s something pretty similar.

The good thing about being able to include code in an interface is that you can use composition in a much more powerful way. We’ll see in a minute.

Interfaces in Java 6

The problem with Java interfaces is that we can only describe behavior, but not implement it.

This is enough in many cases. But there are situations that we can’t solve, because it forces us to delegate the implementation of this interface in individual objects if we want to achieve a good composition.

All this makes something as simple composing the code of a class using reusable pieces rather complicated.

Interfaces in Kotlin

Kotlin brings us some very good news: interfaces can have code.

This means that we can implement a kind of multiple inheritance (somewhat limited, in any case). We can make a class implement several interfaces, and inherit the behavior from each one.

Want to learn Kotlin?

Check my free guide to create your first project in 15 minutes!

To write an interface that includes some methods implemented, you don’t need anything special:

12345 interfaceInterface1{fun function1(){Log.d("Interface1","function1 called")}}

We could have another interface 2 with another function:

12345 interfaceInterface2{fun function2(){Log.d("Interface2","function2 called")}}

And a class that implements them could use both without problem:

123456 classMyClass:Interface1,Interface2{fun myFunction(){function1()function2()}}

Great! This gives us much more versatility when organizing our code.

Interfaces can’t keep state

It’s an important limitation to keep in mind. We can have code but not state.

This means that we can’t create a property and store the state in it. If we define a property in an interface, the class that implements it needs to overwrite it.

Let’s see an example. Imagine that the interface needs a context:

1234567 interfaceToaster{val context:Contextfun toast(message:String){Toast.makeText(context,message,Toast.LENGTH_SHORT).show()}}

The code is simple. It’s an interface that implements a method that displays a Toast. It requires a context to do that.

If we have an activity that wants to use this interface, it needs to overwrite the context:

12345678 classMyActivity:AppCompatActivity(),Toaster{override val context=thisoverride fun onCreate(savedInstanceState:Bundle?){super.onCreate(savedInstanceState)toast("onCreate")}}

As simple as that. We assign the Activity itself as a context, and the interface will use it.

Now you can use the Toaster functions in the Activity without any problems.

Interface delegation

Another very interesting feature in Kotlin is the interface delegation. It is a very powerful tool to achieve a cleaner composition.

Imagine that you have a class C, composed of two objects of type A and B:

1234567891011121314 interfaceA{fun functionA(){}}interfaceB{fun functionB(){}}classC(vala:A,valb:B){fun functionC(){a.functionA()b.functionB()}}

Class C uses functions A and B within its own code.

If an object is composed by other components, it’d be very good that it could use their functions directly.

There is another way to write this code and get the same result, using the interface delegation:

123456 classC(a:A,b:B):Abya,Bbyb{fun functionC(){functionA()functionB()}}

You can see that class C is implementing A and B, but it’s actually delegating the implementation to the objects it receives as a parameter.

By using interface delegation, the class can use functions from implemented classes directly and still delegate the implementation to other objects.

Conclusion

We’ve seen the differences between Java interfaces and those of Kotlin. Now try to find out what situations can simplify your life, because these new ideas open a world of possibilities.

Your code will be more reusable than before and much more readable.

Still not convinced about Kotlin for Android? Start using it as soon as possible! Thanks to the the previous articles you can learn more about Kotlin, or in the book where you’ll do it by creating a complete App from scratch.

I’m in love with Kotlin. I’ve been learning about it for a couple of years, applying it to Android and digesting all this knowledge so that you can learn it with no effort.

Shares

Like this:

Like Loading...

相關推薦

Interfaces in Kotlin. Who said interfaces can't have code?

The interfaces in Kotlin will allow you to reuse more code than what you can get with Java. The reason is very simple: you can add code to your inter

Ask HN: People who went from “can't” do doing it. What changed?

I feel so overwhelmed by my day job and my general ineptitude that I don't think I'll ever be able to found anything, yet the rational brain knows this is

mysql報錯:SQLSTATE[42000]: Syntax error or access violation: 1101 BLOB/TEXT column ‘rule’ cant have a default value

多次遇到這個問題了,今天特意記錄一下: SQLSTATE[42000]: Syntax error or access violation: 1101 BLOB/TEXT column 'city' can't have a default value  解決辦法: windows在my.in

解決UnicodeDecodeError: ‘ascii’ codec cant decode byte 0xe5 in position 108: ordinal not in range(128)

style 資料 spa 和數 cnblogs ref lib utf 其中   今天做網頁到了測試和數據庫交互的地方,其中HTML和數據庫都是設置成utf-8格式編碼,插入到數據庫中是正確的,但是當讀取出來的時候就會出錯,原因就是Python的str默認是ascii編碼,

Cant update table ‘xxx’ in stored function/trigger because it is already used by statement which invoked this stored function/trigger

error trigger 操作 xxx ready 觸發 sql tab 觸發器 MySQL: Solution for ERROR 1442 (HY000): Can’t update table ‘xxx’ in stored function/trigger bec

UnicodeDecodeError: ‘ascii’ codec cant decode byte 0xbd in position 11: ordinal not in range(128)

Windows預設的編碼方式是GBK   在使用python呼叫matlab相關的patplotlib.pyplot庫進行畫圖操作時遇到“UnicodeDecodeError: ‘ascii’ codec can’t decode byte 0xbd in position 11:

Yet another tool to mock interfaces in Go

Yet another tool to mock interfaces in Go https://itnext.io/yet-another-tool-to-mock-interfaces-in-go-73de1b02c041 As a powerful tool, uni

‘unicodeescape’ codec cant decode bytes in position XXX: trun 解決方法

錯誤原因,\ 被當做轉義字元使用,因此找不到路徑地址 txt = open("C:\Users\xyz\Desktop\Hamlet.txt", "r").read()   解決方法,採用以下方法描述路徑 方式一:轉義的方式 'd:\\a.txt' 方式二:顯式宣告字串

macOS解決sublime text3執行python3報:UnicodeEncodeError: 'ascii' codec can't encode characters in position

問題背景:macOS剛裝上python3和sublime test,匯入原來在windows上寫的python指令碼(在windows上執行正常),執行後報錯UnicodeEncodeError: 'ascii' codec can't encode characters i

Python 中 'unicodeescape' codec can't decode bytes in position XXX: trun { cv.imread()的使用)}錯誤解決方案

背景描述 今天在運用Python pillow模組處理圖片時遇到一個錯誤 cv.imread("D:\image\1.jpg") 然後報錯 SyntaxError: (unicode error) 'unicodeescape' codec can't

python讀取txt檔案的錯誤 gbk' codec can't decode byte 0xbf in position 2: illegal multibyte sequence”的解決辦法

眾所周知 ,python對檔案讀寫不友好 在我匯入一個新建utf-8 txt檔案依然報錯之後 最終 data11=open("D:/Downloads/盜墓筆記全集.txt").read().en

"svnserve: Can't bind server socket: Address already in use"報錯解決方法

問題原因 svn的埠衝突導致 當我們啟動svn服務後,系統會預設開啟的埠3690。當你啟動了一個版本庫後,再次啟動另外的版本庫,由於沒有指定埠號,這個版本庫還是會去使用3690埠,因此導致衝突。

exception1:unicodeescape’ codec cant decode bytes in position XXX: trun錯誤解決方案

pro 三種 描述 exce 轉義 osi 字符串 esc code window 讀取文件可以用\,但是在字符串中\是被當作轉義字符來使用,所以’d:\a.txt’會被轉義成’d:\a.txt’這是正確路徑,所以不會報錯。而‘C:\Users\FrankYuan\Pict

MySQL 中 You can't specify target table '表名' for update in FROM clause錯誤

在MySQL中,寫SQL語句的時候 ,可能會遇到You can't specify target table '表名' for update in FROM clause這樣的錯誤,它的意思是說,不能先select出同一表中的某些值,再更新這個表(在同一語句中),即不能依據某

【svn】【svn啟動】解決svnserve: Can't bind server socket: Address already in use

最近在忙著搭建jenkins系統整合版本控制和git分散式版本控制,其中涉及到了點svn方面的,由於自己也是第一次搭建svn,挺順利的,中間遇到點小問題: 我使用的是yum安裝的svn,安裝完成配置結束。 /etc/init.d/svnserve start   ok

Python中SyntaxError: (unicode error) 'unicodeescape' codec can't decode bytes in position 2-3: ***錯誤

前幾天一直在對檔案的寫入、刪除等操作學習,但是複製檔案的路徑一直報錯對檔案操作不了,所以一直把檔案複製到pychrome當前專案的目錄中使用,現在總結下怎麼使用非當前目錄下的檔案。 fh=logging.FileHandler("C:\Users\huang\Pycharm

解決 UnicodeEncodeError: 'ascii' codec can't encode characters in position 16-20: ordinal not in range

python中因編碼問題報錯: Traceback (most recent call last): File "a*.py", line 61, in <module> m*w

python 字串輸出報錯 'utf-8' codec can't encode characters in position

一些字串無法被utf-8解碼,所以可以把無法轉化為utf-8格式的字元‘ignore’掉,再進行解碼。 str().encode('UTF-8', 'ignore').decode('UTF-8') 測試程式碼:  text = ''' '\n

解決UnicodeDecodeError: 'utf-8' codec can't decode byte 0xff in position 0: invalid start byte問題

本文最後更新於2018-6-20,可能會因為沒有更新而失效。如已失效或需要修正,請聯絡我! 早上在用Flask框架時出現了這個問題,我在原始碼裡寫的是 @app.route('/hello') def hello(): return render_te

python執行時出現UnicodeDecodeError: 'gbk' codec can't decode byte 0x89 in position 14: illegal ...的解決辦法

在python第四次實驗作業時: python在讀取檔案時出現“UnicodeDecodeError: 'gbk' codec can't decode byte 0x89 in position 14: illegal multibyte sequence”錯誤 翻譯為